我需要这样将很大的数字格式化为数十亿或数百万:
$ 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 */
最佳答案
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?