如何在 JavaScript 中使用 toLocaleString() 和 tofixed(2)

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

How to use toLocaleString() and tofixed(2) in JavaScript

javascript

提问by Question User

How can I do this in JavaScript?

我怎样才能在 JavaScript 中做到这一点?

var num = 2046430; 
num.toLocaleString();

will give you "2,046,430";

What I have tried is:

我尝试过的是:

var num = 2046430; 
num.toLocaleString().toFixed(2);

Expected Output

预期产出

"2,046,430.00"

“2,046,430.00”

回答by Sebastian Nette

Taken from MDN:

摘自 MDN:

Syntax

句法

numObj.toLocaleString([locales [, options]])

numObj.toLocaleString([locales [, options]])

toLocaleStringtakes 2 arguments. The first is the locale, the second are the options. As for the options, you are looking for:

toLocaleString需要 2 个参数。第一个是语言环境,第二个是选项。至于选项,您正在寻找:

minimumFractionDigits

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).

最小分数

要使用的最小小数位数。可能的值是从 0 到 20;普通数字和百分比格式的默认值为 0;货币格式的默认值是 ISO 4217 货币代码列表提供的次要单位位数(如果列表不提供该信息,则为 2)。

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

To be able to set the options without setting the locale, you can pass undefined as first argument:

为了能够在不设置语言环境的情况下设置选项,您可以将 undefined 作为第一个参数传递:

var num = 2046430;
num.toLocaleString(undefined, {minimumFractionDigits: 2}) // 2,046,430.00

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)

然而,这也允许分数长于 2 位数。所以我们需要寻找一个名为maximumFractionDigits. (也在那个 MDN 页面上)

var num = 2046430.123;
num.toLocaleString(undefined, {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
}) // 2,046,430.12