我需要将真正大数字格式化为数十亿或数百万像这样:
$ 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 */
答案 0 :(得分:0)
function nFormatter(num, digits) {
var si = [
{ value: 1E18, symbol: "E" },
{ value: 1E15, symbol: "P" },
{ value: 1E12, symbol: "T" },
{ value: 1E9, symbol: "G" },
{ value: 1E6, symbol: "M" },
{ value: 1E3, symbol: "k" }
], i;
for (i = 0; i < si.length; i++) {
if (num >= si[i].value) {
return (num / si[i].value).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, "$1") + si[i].symbol;
}
}
return num.toString();
}
console.log(nFormatter(123, 1)); // 123
console.log(nFormatter(1234, 1)); // 1.2k
console.log(nFormatter(100000000, 1)); // 100M
console.log(nFormatter(299792458, 1)); // 299.8M
console.log(nFormatter(759878, 1)); // 759.9k
console.log(nFormatter(759878, 0)); // 760k
How to format a number as 2.5K if a thousand or more, otherwise 900 in javascript?
答案 1 :(得分:0)
您可以使用像这样的函数来包装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,其中包含许多测试,其中包含locale
和currency
的一些组合。
答案 2 :(得分:-1)
您可以使用以下功能:
function formatB(n) {
if (n > 999999999)
return "$" + (n/1000000000).toFixed(2) + "B";
else if(n > 999999)
return "$" + (n/1000000).toFixed(2) + "M";
else
return n;
}