-
format numbers output?
hey, is there any way that i can format the output of the numbers, like a print mask or something?
im printing out dollar ammounts, and right now it is say...$1000, is there any way to make it print $1,000...and other numbers such as $1,000,000,000 or something? thanks for your help
-
Code:
void
printNumber (int num) {
//big enough to hold number
char s_num[100];
// s_num length
int len = 0;
sprintf( s_num, "%d", num );
len = strlen(s_num);
printf("$");
for (int i=0;i<len;i++) {
printf("%c", s_num[i]);
// if we must print a ","
if ((len-(i+1))%3==0 && len-i!=1)
printf(",");
}
printf("\n");
}
-
Very C.
As I said in your other post. Another option is to use stringstreams and substrings.
-
This prints out $12,345.68:
Code:
std::cout.imbue(std::locale("en_US"));
std::cout << std::fixed << std::setprecision(2);
std::cout << "$" << 12345.678 << std::endl;
(Don't forget that setprecision requires "#include <iomanip>")
Note that if you ever need to translate this program and handle other currency formats the only thing you need to change the "en_US" string.. and the dollar symbol. No need to look up the decimal and thousands separators from some reference.
-
Er... I tryed a better C++ solution, but couldnīt find anything to help me. :o