js number format All In One

xgqfrms / 2023-05-21 / 原文

js number format All In One

金融数据表示法

千分位符号

// 1,000,000

Number Format

const number = 123456.789;

console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// Expected output: "123.456,79 €"

// The Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// Expected output: "¥123,457"

// Limit to three significant digits
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));
// Expected output: "1,23,000"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat

new Intl.NumberFormat()
new Intl.NumberFormat(locales)
new Intl.NumberFormat(locales, options)

Intl.NumberFormat()
Intl.NumberFormat(locales)
Intl.NumberFormat(locales, options)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat

number.toLocaleString(locale, options);

https://simplelocalize.io/blog/posts/number-formatting-in-javascript/

demos

const number = 123456.789;

// ✅
// const rmb = new Intl.NumberFormat('zh-Hans-CN', {
// ✅
// const rmb = new Intl.NumberFormat('zh-Hans', {
// ✅
const rmb = new Intl.NumberFormat('zh-CN', {
  style: 'currency',
  // currency: 'RMB', ❌
  currency: 'CNY',
}).format(number);

console.log(`RMB =`, rmb);
// Expected output: "¥123,457.789"

// RMB = ¥123,456.79 ❓❓❓

image

currency code

RMB

CNY

https://en.wikipedia.org/wiki/ISO_4217

image

const nf = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 2,
  roundingIncrement: 5,
});

console.log(nf.format(11.29)); // "$11.30"
console.log(nf.format(11.25)); // "$11.25"
console.log(nf.format(11.22)); // "$11.20"

locales

BCP 47 language tag

https://www.rfc-editor.org/info/bcp47

https://www.rfc-editor.org/rfc/inline-errata/rfc4646.html

zh-CN Chinese China Mainland China, simplified characters

https://www.techonthenet.com/js/language_tags.php

refs



©xgqfrms 2012-2021

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!