gpt4 book ai didi

javascript - 如何将数字格式化为货币字符串

转载 作者:bug小助手 更新时间:2023-10-28 10:41:44 25 4
gpt4 key购买 nike

我想用 JavaScript 格式化价格。我想要一个以 float 作为参数并返回格式如下的 string 的函数:

"$ 2,500.00"

我该怎么做?

最佳答案

Intl.NumberFormat

JavaScript 有一个数字格式化程序(国际化 API 的一部分)。

// Create our number formatter.
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',

// These options are needed to round to whole numbers if that's what you want.
//minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1)
//maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501)
});

console.log(formatter.format(2500)); /* $2,500.00 */

使用 undefined 代替第一个参数(示例中为 'en-US')以使用系统区域设置(如果代码正在运行,则为用户区域设置在浏览器中)。 Further explanation of the locale code .

这是 list of the currency codes .

Intl.NumberFormat 与 Number.prototype.toLocaleString

最后说明将其与旧的 .toLocaleString 进行比较。它们都提供基本相同的功能。然而,toLocaleString 在它的旧版本(pre-Intl)does not actually support locales : 它使用系统语言环境。因此,在调试旧浏览器时,请确保您使用的是正确的版本 (MDN suggests to check for the existence of Intl)。如果您不关心旧浏览器或只使用 shim,则根本无需担心这一点。 .

此外,对于 单个 项,两者的性能相同,但如果您有很多数字要格式化,使用 Intl.NumberFormat 大约是 70 次快点。因此,通常最好使用 Intl.NumberFormat 并且每次页面加载只实例化一次。无论如何,这是 toLocaleString 的等效用法:

console.log((2500).toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
})); /* $2,500.00 */

关于浏览器支持和 Node.js 的一些说明

  • 浏览器支持如今已不再是问题,全局 98% 的支持,美国 99% 和欧盟 99% 以上的支持
  • 有一个shim如果你真的需要在化石浏览器(如 Internet Explorer 8 )上支持它
  • v13 之前的 Node.js 仅支持 en-US 开箱即用。一种解决方案是安装 full-icu ,见 here了解更多信息
  • 看看CanIUse了解更多信息

关于javascript - 如何将数字格式化为货币字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/149055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com