如何在javascript中使用toLocaleString()和tofixed(2) [英] how to use toLocaleString() and tofixed(2) in javascript
问题描述
我如何在javascript中执行此操作?
How can i do this in javascript ?
var num = 2046430;
num.toLocaleString();
will give you "2,046,430";
我试过的是
var num = 2046430;
num.toLocaleString().toFixed(2);
预期输出
"2,046,430.00";
推荐答案
摘自MDN:
语法
numObj.toLocaleString([locales [,options]])
toLocaleString
需要2个参数。第一个是区域设置,第二个是选项。至于期权,您正在寻找:
toLocaleString
takes 2 arguments. The first is the locale, the second are the options. As for the options, you are looking for:
minimumFractionDigits
minimumFractionDigits
最低价格要使用的小数位数。
可能的值为0到20;普通数字的默认值和
%格式为0;货币格式的默认值是ISO 4217货币代码
列表提供的
次要单位数字(如果列表未提供该信息,则为2)。
The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information).
https:// developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
为了能够在不设置选项的情况下设置选项在locale中,您可以将undefined作为第一个参数传递:
To be able to set the options without setting the locale, you can pass undefined as first argument:
var num = 2046430;
num.toLocaleString(undefined, {minimumFractionDigits: 2}) // 2,046,430.00
然而这也允许分数长于2位数。因此,我们需要寻找另一个名为 maximumFractionDigits
的选项。 (也在该MDN页面上)
However this also allows the fraction to be longer than 2 digits. So we need to look for one more option called maximumFractionDigits
. (Also on that MDN page)
var num = 2046430.123;
num.toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
}) // 2,046,430.12
这篇关于如何在javascript中使用toLocaleString()和tofixed(2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!