Got a question about printing Integers with thousands/millions separator.
I got a Textfile where i got Country, City,Total Population.
I have to read in the File, and sort by country. If country is eual, i have to sort descending by population.
Textfile is like:
Australia........Sydney.........10.123.456
Brazil...........Sao Paulo.......7.123.345
I read all 3 into a seperated string. Then i erase all "." in the population string. Then i use atoi() to cast the population string to an integer.
Now i can sort by population if country is equal. This sort works correctly.
So far so good. But i need to get thousand/millions seperator into the printing of the population.
If i use string,with the "." for population, sorting dont work correctly. Its sorted like:
x........x......1.123456
x........x......10.123.456
x........x......2.123.232
It have to look like:
Australia........Sydney.........10.123.456
Australia........Brisbane.......8.123.456
Is there a way to manipulate the printing by adding separator the the int again?
Many Thanks in advance
we can use my_string = '{:,. 2f}'. format(my_number) to convert float value into commas as thousands separators.
Per Format Specification Mini-Language, The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.
imbue()
the output stream with a locale that has the desired separator. For example:
#include <iostream>
#include <locale>
int main()
{
// imbue the output stream with a locale.
int i = 45749785;
std::cout << i << "\n";
std::cout.imbue(std::locale(""));
std::cout << i << "\n";
}
Output on my machine (and online demo):
45749785 45,749,785
As commented, and answered, by James Kanze imbue the input stream also to read the separated int
values without manually modifying the input.
See Stroustrop's Appendix D: Locales for a detailed overview of locales.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With