今天记录一个构造方法可以轻而易举的对数字进行千分位处理小数处理等。
先贴上官方API:点击进入
examples
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"
const amount = 3500;
console.log(new Intl.NumberFormat().format(amount));
// '3,500' if in US English locale
const amount = 3500;
new Intl.NumberFormat("en-US", {
style: "decimal",
}).format(amount); // '3,500'
new Intl.NumberFormat("en-US", {
style: "percent",
}).format(amount); // '350,000%'
const amount = 3500;
new Intl.NumberFormat("en-US", {
style: "unit",
unit: "liter",
}).format(amount); // '3,500 L'
new Intl.NumberFormat("en-US", {
style: "unit",
unit: "liter",
unitDisplay: "long",
}).format(amount); // '3,500 liters'
// Formatting adds zeros to display minimum integers and fractions
console.log(
new Intl.NumberFormat("en", {
minimumIntegerDigits: 3,
minimumFractionDigits: 4,
}).format(4.33),
);
// "004.3300"
// Display value shortened to maximum number of digits
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 2,
}).format(4.33145),
);
// "4.33"
// Minimum fractions have no effect if value is higher precision.
console.log(
new Intl.NumberFormat("en", {
minimumFractionDigits: 2,
}).format(4.33145),
);
// "4.331"
更多api详见官方API