在 C 中打印带有逗号的浮点数

Jw1*_*123 0 c floating-point floating-point-conversion

可能的重复:
将 1000000 输出为 1,000,000 等等

我有一个格式为 xxxxxxxx.xx 的浮点变量(例如 11526.99)。我想将其打印为 11,562.99,并带有逗号。C语言中如何插入逗号?

dre*_*lax 5

尝试:

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

int main()
{
    float f = 12345.67;

    // obtain the existing locale name for numbers    
    char *oldLocale = setlocale(LC_NUMERIC, NULL);

    // inherit locale from environment
    setlocale(LC_NUMERIC, "");

    // print number
    printf("%'.2f\n", f);

    // set the locale back
    setlocale(LC_NUMERIC, oldLocale);
}
Run Code Online (Sandbox Code Playgroud)

这取决于当前的区域设置。C 和 POSIX 语言环境没有千位分隔符。您可以自行将其设置为您知道使用千位分隔符的区域设置,而不是从环境继承区域设置。在我的系统上,使用"en_NZ"提供了千位分隔符。