在C中用逗号打印一个浮点数 [英] Printing a float with commas in C

查看:172
本文介绍了在C中用逗号打印一个浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


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

我有一个格式为xxxxxxxx.xx的float变量(例如11526.99)。我想用逗号将其打印为11,562.99。如何在C中插入逗号?

I have a float variable in the format xxxxxxxx.xx (Eg. 11526.99). I'd like to print it as 11,562.99 with a comma. How can I insert a comma in C?

推荐答案

试试:

Try:

#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);
}

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

This depends on the current locale. The C and POSIX locales do not have a thousands separator. Instead of inheriting the locale from the environment you can set it yourself to a locale that you know uses a thousands separator. On my system, using "en_NZ" provides a thousands separator.

这篇关于在C中用逗号打印一个浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆