问题描述
我正在寻找将 Long Float 格式化为 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("你欠你 $%.2Lf!", 钱);
printf("You are owed $%.2Lf!", money);
返回类似的东西
欠你 123456789.00 美元!
数字应该看起来像这样
$123,456,789.00
$1,234.56
$123.45
任何答案都不需要在实际代码中.你不必用勺子喂食.如果有与 c 相关的细节会有所帮助,请提及.其他伪代码就好了.
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.
谢谢.
推荐答案
您的 printf
可能已经能够通过 '
标志自行完成.不过,您可能需要设置您的语言环境.这是我机器上的一个例子:
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;
}
并运行它:
> make example
clang -Wall -Wextra -Werror example.c -o example
> ./example
$123,456,789.00
$1,234.56
$123.45
这个程序在我的 Mac (10.6.8) 和我刚刚尝试过的 Linux 机器 (Ubuntu 10.10) 上都能按照你想要的方式运行.
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.
这篇关于如何在 C 中用逗号格式化货币?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!