Javascript 数字和货币本地化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5624173/
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 17:48:26  来源:igfitidea点击:

Javascript Number and Currency localization

javascriptlocalization

提问by Dan

I've run into numbers and currency localization in JavaScript

我在 JavaScript 中遇到过数字和货币本地化

What I need is a convenient libraryfor that.

我需要的是一个方便的图书馆

I am responsible for setting the decimal separators, currency, etc.

我负责设置小数点分隔符、货币等。

Please post the best links you think

请发布您认为最好的链接

回答by Ian Chadwick

Most modern browsershave built in support internationalisationin the form of the global Intl object and extensions to Number, String & Date.

大多数现代浏览器都以全局 Intl 对象和对数字、字符串和日期的扩展的形式支持国际化

var money = 123456.12;

// display with correct formatting
money.toLocaleString('de-DE'); // "123.456,12"

// for currency, bad as we're leaving the precision to the gods of floating point numbers
money.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' }); // "£123,456.12"

// for currency, good as we're using strings...
new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format('12312.12')

If you're not familiar with why floating point numbers are bad for currency info check this out on floating point numbers

如果您不熟悉为什么浮点数对货币信息不利,请查看浮点数

回答by Gabe Moothart

The best answer for you probably depends on what javascript libary, if any, you are currently using. But YUI has support for number/currency formatting with internationalization, and it is a solid and well-designed library.

对您来说最好的答案可能取决于您当前使用的 javascript 库(如果有)。但是 YUI 支持具有国际化的数字/货币格式,它是一个可靠且设计良好的库。

Example:

例子:

alert(Y.DataType.Number.format(123123123.176,{
    prefix: "",
    thousandsSeparator: ".",
    decimalSeparator: ",",
    decimalPlaces: 2,
    suffix: " (EUR)"
}));

回答by GBL

This post is quite old, but I post a response in case it's interesting someone.

这篇文章已经很旧了,但我会发布回复以防有人感兴趣。

I found the numeral.jslibrary pretty useful to do this.
You can define your custom formats and add localized files in the same way that 'moment.js'.

我发现numeric.js库在这方面非常有用。
您可以定义自定义格式并以与“moment.js”相同的方式添加本地化文件。

You should probably check to see if it fits your needs.

您可能应该检查一下它是否符合您的需求。