如何使用 JavaScript 格式化数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5882994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:39:58  来源:igfitidea点击:

How to format numbers using JavaScript?

javascriptlocalization

提问by Kanak Vaghela

I want to format number using javascript as below:

我想使用 javascript 格式化数字,如下所示:

10.00=10,00 
1,000.00=1.000,00

回答by Andy E

Every browser supports Number.prototype.toLocaleString(), a method intended to return a localized string from a number. However, the specification defines it as follows:

每个浏览器都支持Number.prototype.toLocaleString(),一种旨在从数字返回本地化字符串的方法。但是,规范将其定义如下:

Produces a string value that represents the value of the Number formatted according to the conventions of the host environment's current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.

生成一个字符串值,该值表示根据主机环境当前语言环境的约定格式化的 Number 值。此函数是依赖于实现的,允许但不鼓励它返回与toString.

Implementation-dependant means that it's up to the vendor how the result will look, and results in interoperability issues.

依赖于实现意味着结果的外观取决于供应商,并导致互操作性问题。

Internet Explorer(IE 5.5 to IE 9) comes closest to what you want and formats the number in a currency style - thousands separator and fixed at 2 decimal places.

Internet Explorer(IE 5.5 到 IE 9)最接近您想要的,并以货币样式格式化数字 - 千位分隔符并固定为 2 个小数位。

Firefox(2+) formats the number with a thousands separator and decimal places but only if applicable.

Firefox(2+) 使用千位分隔符和小数位格式化数字,但前提是适用。

Opera, Chrome & Safarioutput the same as toString()-- no thousands separator, decimal place only if required.

Opera、Chrome 和 Safari输出相同toString()- 没有千位分隔符,仅在需要时使用小数位。

Solution

解决方案

I came up with the following code (based on an old answer of mine) to try and normalize the results to work like Internet Explorer's method:

我想出了以下代码(基于我的一个旧答案)来尝试将结果标准化,使其像 Internet Explorer 的方法一样工作:

(function (old) {
    var dec = 0.12 .toLocaleString().charAt(1),
        tho = dec === "." ? "," : ".";

    if (1000 .toLocaleString() !== "1,000.00") {
        Number.prototype.toLocaleString = function () {
           var neg = this < 0,
               f = this.toFixed(2).slice(+neg);

           return (neg ? "-" : "") 
                  + f.slice(0,-3).replace(/(?=(?!^)(?:\d{3})+(?!\d))/g, tho) 
                  + dec + f.slice(-2);
        }
    }
})(Number.prototype.toLocaleString);

This will use the browser's built-in localization if it's available, whilst gracefully degrading to the browser's default locale in other cases.

如果可用,这将使用浏览器的内置本地化,同时在其他情况下优雅地降级到浏览器的默认语言环境。

Working demo: http://jsfiddle.net/R4DKn/49/

工作演示:http: //jsfiddle.net/R4DKn/49/

回答by learango

I know this solution using NumberFormat but it is necessary to convert the values to string. https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/NumberFormat

我知道这个使用 NumberFormat 的解决方案,但有必要将值转换为字符串。 https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/NumberFormat

// Remove commas
number = "10,000.00".replace(/,/g, '');

// Create a NumberFormat type object
var formatter = new Intl.NumberFormat('de-DE', {
    minimumFractionDigits: 2
}); 

// Apply format
console.log(formatter.format(number));

output:10.000,00

回答by Spudley

Javascript doesn't provide this functionality itself, but there are a number of third-party functions around which can do what you want.

Javascript 本身不提供此功能,但有许多第三方功能可以执行您想要的操作。

Note, whichever method you use, you should be careful to only use the resulting string for display purposes -- it won't be a valid number value in Javascript after you've converted the decimal point to a comma.

请注意,无论您使用哪种方法,都应注意仅将结果字符串用于显示目的——在将小数点转换为逗号后,它在 Javascript 中将不是有效的数值。

The quickest solution I can offer is to use the number_format()function written by the phpJS people. They've implemented Javascript versions of a load of commonly-used PHP functions, including number_format(), and this function will do exactly what you want.

我能提供的最快的解决方案是使用number_format()phpJS 人编写的函数。他们已经实现了大量常用 PHP 函数的 Javascript 版本,包括number_format(),并且该函数将完全满足您的要求。

See the link here: http://phpjs.org/functions/number_format

请参阅此处的链接:http: //phpjs.org/functions/number_format

I wouldn't bother about taking the whole phpJS library (a lot of it is of questionable value anyway), but just grab the 20-odd line function shown on the page linked above and paste it into your app.

我不会考虑获取整个 phpJS 库(无论如何,其中很多都具有可疑的价值),但只需获取上面链接页面上显示的 20 多行函数并将其粘贴到您的应用程序中即可。

If you want a more flexible solution, there are a number of JS functions around which simulate the printf()function from C. There is already a good question on SO covers this. See here: JavaScript equivalent to printf/string.format

如果你想要一个更灵活的解决方案,有许多 JS 函数可以模拟printf()C 中的函数。 SO 上已经有一个很好的问题涵盖了这一点。请参阅此处:JavaScript 等效于 printf/string.format

Hope that helps.

希望有帮助。