是否有内置函数用逗号分隔C,C ++或JavaScript中的数字?

鉴于数字为12456789 ,我需要在没有太多编码的情况下输出12,456,789 。 我可以使用C,C ++或JavaScript中的任何内置函数吗?

我发现这个小的javascript函数可以工作( 源码 ):

 function addCommas(nStr){ nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } 

是的,这可以通过在语言环境中设置正确的方面在C ++中自动完成。

 #include  #include  #include  template struct Sep : public std::numpunct { virtual std::string do_grouping() const {return "\003";} }; int main() { std::cout.imbue(std::locale(std::cout.getloc(), new Sep ())); std::cout << 123456789 << "\n"; } 

注意:C语言环境(应用程序未专门设置时使用的语言环境)不使用千位分隔符。 如果您将应用程序的语言环境设置为特定语言,那么它将选择特定于语言的分组方法(无需执行上述任何操作)。 如果要将语言环境设置为机器当前语言设置(由OS定义)而不是特定语言环境,则使用“”(空字符串)作为语言环境。

因此,要根据您的操作系统特定设置设置区域设置:

 int main() { std::cout.imbue(std::locale("")); std::cout << 123456789 << "\n"; } 

在C ++中,您通常使用以下内容:

 std::locale loc(""); std::cout.imbue(loc); std::cout << 1234567; 

具有如此使用的空名称的区域设置不一定完全按照您在上面指定的格式编号。 相反,它从系统的其余部分获取区域设置,并适当格式化,所以对我来说(我的系统设置为美国)它会产生“1,234,567”,但如果系统设置为(大多数部分) )欧洲,它将产生“1.234.567”。

在一些C编译器实现中,为printf函数提供了扩展,以便在数字格式说明符中用作修饰符的单引号/撇号字符将执行“千位分组”:

 #include  #include  int main(void) { printf( "%'d\n", 1234567); setlocale(LC_NUMERIC, "en_US"); printf( "%'d\n", 1234567); return 0; } 

将产生(无论如何GCC 4.4.1):

 1234567 1,234,567 

不幸的是,这种扩展并未得到特别广泛支持。

//另一个javascript方法,适用于数字

 Number.prototype.withCommas= function(){ return String(this).replace(/\B(?=(?:\d{3})+(?!\d))/g,',') } var n=12456789.25; alert(n.withCommas()); 

/ *返回值:(String)12,456,789.25 * /

对于C ++,您可以尝试:

 std::locale get_numpunct_locale(std::locale locale = std::locale("")) { #if defined(_MSC_VER) && defined(_ADDFAC) && (!defined(_CPPLIB_VER) || _CPPLIB_VER < 403) // Workaround for older implementations std::_ADDFAC(locale, new std::numpunct()); return locale; #else return std::locale(locale, new std::numpunct()); #endif } template std::string nformat(T value) { std::ostringstream ss; ss.imbue(get_numpunct_locale()); ss << value; return ss.str(); }