我想用 JavaScript 格式化价格。我想要一个需要一个函数float
作为参数并返回string
格式如下:
"$ 2,500.00"
我怎样才能做到这一点?
国际数字格式 https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/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 */
Use undefined
代替第一个参数('en-US'
在示例中)使用系统区域设置(代码在浏览器中运行时的用户区域设置)。区域设置代码的进一步解释 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation.
这是一个货币代码列表 https://www.iban.com/currency-codes.
Intl.NumberFormat 与 Number.prototype.toLocaleString
最后一点是将其与旧版本进行比较。toLocaleString
。它们都提供本质上相同的功能。然而,toLocaleString 的旧版本(前 Intl)实际上并不支持语言环境 http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4.3:它使用系统区域设置。因此,在调试旧浏览器时,请确保您使用的是正确的版本(MDN 建议检查是否存在Intl https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Checking_for_support_for_locales_and_options_arguments)。如果您不关心旧浏览器或只是使用shim https://github.com/andyearnshaw/Intl.js.
而且,两者的性能对于single项目,但如果您有很多数字需要格式化,请使用Intl.NumberFormat
快约 70 倍。因此,通常最好使用Intl.NumberFormat
并且每次页面加载仅实例化一次。无论如何,这是等效的用法toLocaleString
:
console.log((2500).toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
})); /* $2,500.00 */
关于浏览器支持和 Node.js 的一些说明
- 如今,浏览器支持不再是问题,全球支持率超过 99%
- 有一个shim https://github.com/andyearnshaw/Intl.js在化石浏览器上支持它(例如互联网浏览器 8 https://en.wikipedia.org/wiki/Internet_Explorer_8),如果你真的需要
- v13之前的Node.js仅支持
en-US
盒子外面。一种解决方案是安装full-icu https://github.com/icu-project/full-icu-npm, see here https://stackoverflow.com/a/39626602/1000608了解更多信息
- 看一下CanIUse https://caniuse.com/#feat=internationalization了解更多信息
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)