JQuery数字格式

Era*_*dan 38 javascript jquery number-formatting

关于这个基本功能有太多的问题和答案,我看不到树木的木材.

在Java中,只有一个简单的答案(java.text.NumberFormat及其子类),所以我确信大多数插件,问题和答案最终都会成熟为JQuery的事实标准.

这个插件是我迄今为止发现的最好的插件,但我不知道它是否仍在开发中,是否成熟等.

http://plugins.jquery.com/project/numberformatter

有更好的解决方案吗?它是否足够成熟/活跃?


编辑:

我希望能够基于Java使用的相同格式模式格式化货币,十进制,整数,以便可以格式化客户端收到的数据,而无需先将其发送到服务器.

例如

格式1000$1,0001,000.00等(语言环境支持很好)

似乎http://plugins.jquery.com/project/numberformatter完成了这项工作,但问题是:"我使用的是正确的吗?" 或者"有更好的方法吗?"

Abe*_*ler 67

我建议看看这篇关于如何使用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;
}
Run Code Online (Sandbox Code Playgroud)

来源:http://www.mredkj.com/javascript/numberFormat.html

虽然jQuery可以通过百万种不同的方式让你的生活更轻松,但我认为这样做太过分了.请记住,jQuery可能相当大,当您在页面上使用它时,用户的浏览器需要下载它.

当你使用jQuery时,你应该退后一步,询问它是否足以证明下载库的额外开销.

如果您需要某种高级格式(如您链接的插件中的本地化内容),或者您已经包含jQuery,那么可能值得查看jQuery插件.

旁注 - 如果你想对过度使用jQuery轻笑一下,请检查一下.

  • 我用这段代码制作了一个jQuery插件.现在很容易应用于页面中的多个位置:`$('.number').formatNumber();`.默认是make 1343034.09进入1,343,034.09 - https://github.com/RaphaelDDL/jquery.formatNumber (4认同)

Qua*_*nt6 19

使用jQuery Number Format插件,您可以通过以下三种方式之一获取格式化的数字:

// Return as a string
$.number( 1234.5678, 2 ); // Returns '1,234.57'

// Place formatted number directly in an element:
$('#mynum').number( 1234.5678 ); // #mynum would then contain '1,235'

// Replace existing number values in any element
$('span.num').number( true, 2 ); // Formats and replaces existing numbers in those elements.
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢该格式,或者您需要进行本地化,则可以使用其他参数来选择数字的格式:

.nu​​mber(theNumber,decimalPlaces,decimalSeparator,thousandsSeparator)

您还可以从GitHub获取jQuery数字格式.

  • 在Stack Overflow中可以看到包含对文档记录源的外部引用,但重要的是在答案中包含来自外部源的最重要/相关的片段,并给出关于如何回答问题的背景. (5认同)

小智 5

我在Abe Miessler addCommas 函数的基础上编写了一个 PHP 函数number_format的 JavaScript 模拟。可能有用。

number_format = function (number, decimals, dec_point, thousands_sep) {
        number = number.toFixed(decimals);

        var nstr = number.toString();
        nstr += '';
        x = nstr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? dec_point + x[1] : '';
        var rgx = /(\d+)(\d{3})/;

        while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');

        return x1 + x2;
    }
Run Code Online (Sandbox Code Playgroud)

例如:

var some_number = number_format(42661.55556, 2, ',', ' '); //gives 42 661,56
Run Code Online (Sandbox Code Playgroud)


eli*_*xon 5

浏览器开发进度:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

 Number.toLocaleString(locale);

 // E.g.
 parseFloat("1234567.891").toLocaleString(window.document.documentElement.lang);
 "1,234,567.891"
Run Code Online (Sandbox Code Playgroud)