Nicely formatting numbers in C++

As of C++14, you can use ' as a digit group separator:

auto one_m = 1'000'000;

Previous versions of C++ did not support this natively. There were two major workarounds:

  • Using user-defined literals in C++11; this would allow you to write code as follows:

    auto x = "1_000_000"_i;
    

    (Writing this as a constexpr would be trickier – but is definitely possible.)

  • Using a straightforward macro, which would allow the following code:

      auto x = NUM(1,000,000);
    

There is no way to do this currently. There is, however, a proposal to introduce digit separators (N3499). They haven't yet chosen which character they'd like to use as a separator though. The current suggestions are:

  • Space: 4 815 162 342
  • Grave accent: 4`815`162`342
  • Single quote: 4'815'162'342
  • Underscore: 4_815_162_342

Unfortunately, they all have problems as described in the proposal.

You can take the hacky approach by using a user-defined literal:

long long operator "" _s(const char* cstr, size_t) 
{
    std::string str(cstr);
    str.erase(std::remove(str.begin(), str.end(), ','), str.end());
    return std::stoll(str);
}
 
int main()
{
    std::cout << "4,815,162,342"_s << std::endl;
}

This will print out:

4815162342

It simply removes all of the commas from the given literal and converts it to an integer.


int main()
{
   int x = 1e6;
}

Tags:

C++