Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
679 views
in Technique[技术] by (71.8m points)

formatting - How can I format currency with commas in C?

I'm looking to format a Long Float as currency in C. I would like to place a dollar sign at the beginning, commas iterating every third digit before decimal, and a dot immediately before decimal. So far, I have been printing numbers like so:

printf("You are owed $%.2Lf! ", money);

which returns somehting like

You are owed $123456789.00!

Numbers should look like this

$123,456,789.00
$1,234.56
$123.45

Any answers need not be in actual code. You don't have to spoon feed. If there are c-related specifics which would be of help, please mention. Else pseudo-code is fine.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your printf might already be able to do that by itself with the ' flag. You probably need to set your locale, though. Here's an example from my machine:

#include <stdio.h>
#include <locale.h>

int main(void)
{
    setlocale(LC_NUMERIC, "");
    printf("$%'.2Lf
", 123456789.00L);
    printf("$%'.2Lf
", 1234.56L);
    printf("$%'.2Lf
", 123.45L);
    return 0;
}

And running it:

> make example
clang -Wall -Wextra -Werror    example.c   -o example
> ./example 
$123,456,789.00
$1,234.56
$123.45

This program works the way you want it to both on my Mac (10.6.8) and on a Linux machine (Ubuntu 10.10) I just tried.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...