'Nicely formatting numbers in C++ [duplicate]

In Ada it is possible to write numbers with underscores for separating digits, which greatly improves readability. For example: 1_000_000 (which is equivalent to 1000000) Is there some similar way for C++?

EDIT: This is question about source code, not I/O.

c++


Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

you can always just define a variadic macro, used like N(123,456,678). it's a bit more trouble than it's worth, though. in particular, you may have to workaround some visual c++ peculiarities for portable code for counting arguments.

Solution 4:[4]

What you are looking for is perfectly possible by imbue()ing the I/O stream with the appropriate locale facet (in this case, num_put).

(This is assuming you are talking about I/O. If you are talking about the source itself, that is not possible as of C++11.)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Darshan Rivka Whittle
Solution 2 Lightness Races in Orbit
Solution 3 Cheers and hth. - Alf
Solution 4