gpt4 book ai didi

javascript - 如何使用 toLocaleString 格式化大数字?

转载 作者:行者123 更新时间:2023-11-30 06:52:04 25 4
gpt4 key购买 nike

我需要像这样将非常大的数字格式化为数十亿或数百万:

$ 100.00 B 或 $90.00 M

// this is my code so far:

var currency = doc.stock.exchange.currency; //this is how I get the currency
var formatNumberNat = val.toLocaleString(
'en-US', {
style: 'currency',
currency: currency
}
);
return formatNumberNat; /* €90,102,409,320.00 */

最佳答案

您可以使用像这样的函数来包装 toLocaleString:

const currencyToString = (
num, {
locale = "en-US",
currency = "USD",
minimumFractionDigits = 2,
maximumFractionDigits,
abbreviationFormats
}
) => {
if (num == null || typeof num !== "number") {
// null, undefined, non-numeric, return what was provided
return num;
}

let format;
if (abbreviationFormats != null) {
// formats were provided, find one that works
format = abbreviationFormats.find(f => num >= f.value);
}

if (format != null) {
// apply the format, insert the symbol next to the numeric portion of the formatted string
const {
value,
symbol
} = format;
const formatted = (num / value).toLocaleString(locale, {
style: "currency",
currency,
minimumFractionDigits,
maximumFractionDigits
});
const parts = formatted.match(/([\D]*)([\d.,]+)([\D]*)/)
return `${parts[1]}${parts[2]}${symbol}${parts[3]}`
}

// otherwise, use the number as provided
return num.toLocaleString(locale, {
style: "currency",
currency,
minimumFractionDigits,
maximumFractionDigits
});
};

这将接受可用于缩写大数字的可选格式结构:

const formats = [
{ value: 1e12, symbol: "T" },
{ value: 1e9, symbol: "B" },
{ value: 1e6, symbol: "M" },
{ value: 1e3, symbol: "K" }
];

这是一个codesandbox使用 localecurrency 的一些组合进行了大量测试。

关于javascript - 如何使用 toLocaleString 格式化大数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37799955/

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