我需要显示一个货币值的格式1K等于一千,或1.1K, 1.2K, 1.9K等,如果它不是一个偶数千,否则如果低于一千,显示正常500,100,250等,使用JavaScript格式化的数字?


当前回答

Waylon flynn的答案的修改版本,支持负指数:

function metric(number) { const SI_SYMBOL = [ ["", "k", "M", "G", "T", "P", "E"], // + ["", "m", "μ", "n", "p", "f", "a"] // - ]; const tier = Math.floor(Math.log10(Math.abs(number)) / 3) | 0; const n = tier < 0 ? 1 : 0; const t = Math.abs(tier); const scale = Math.pow(10, tier * 3); return { number: number, symbol: SI_SYMBOL[n][t], scale: scale, scaled: number / scale } } function metric_suffix(number, precision) { const m = metric(number); return (typeof precision === 'number' ? m.scaled.toFixed(precision) : m.scaled) + m.symbol; } for (var i = 1e-6, s = 1; i < 1e7; i *= 10, s *= -1) { // toggles sign in each iteration console.log(metric_suffix(s * (i + i / 5), 1)); } console.log(metric(0));

预期的输出:

   1.2μ
 -12.0μ
 120.0μ
  -1.2m
  12.0m
-120.0m
   1.2
 -12.0
 120.0
  -1.2k
  12.0k
-120.0k
   1.2M
{ number: 0, symbol: '', scale: 1, scaled: 0 }

其他回答

这个函数可以将巨大的数字(正数和负数)转换为读者友好的格式,而不会失去其精度:

function abbrNum(n) { if (!n || (n && typeof n !== 'number')) { return ''; } const ranges = [ { divider: 1e12 , suffix: 't' }, { divider: 1e9 , suffix: 'b' }, { divider: 1e6 , suffix: 'm' }, { divider: 1e3 , suffix: 'k' } ]; const range = ranges.find(r => Math.abs(n) >= r.divider); if (range) { return (n / range.divider).toString() + range.suffix; } return n.toString(); } /* test cases */ let testAry = [99, 1200, -150000, 9000000]; let resultAry = testAry.map(abbrNum); console.log("result array: " + resultAry);

ES2020在Intl中增加了对此的支持。使用如下表示法:

let formatter = Intl。NumberFormat('en',{符号:'紧凑'}); //示例1 让million = formatter.format(1e6); //示例2 Let billion = formatter.format(1e9); / /打印 console.log(million == '1M', billion == '1B');

注意如上所示,第二个示例生成1B而不是1G。 NumberFormat规格:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat https://tc39.es/ecma402#numberformat-objects

注意,目前并不是所有的浏览器都支持ES2020,所以你可能需要这个 Polyfill: https://formatjs.io/docs/polyfills/intl-numberformat

一个简短的替代方案:

function nFormatter(num) { const format = [ { value: 1e18, symbol: 'E' }, { value: 1e15, symbol: 'P' }, { value: 1e12, symbol: 'T' }, { value: 1e9, symbol: 'G' }, { value: 1e6, symbol: 'M' }, { value: 1e3, symbol: 'k' }, { value: 1, symbol: '' }, ]; const formatIndex = format.findIndex((data) => num >= data.value); console.log(formatIndex) return (num / format[formatIndex === -1? 6: formatIndex].value).toFixed(2) + format[formatIndex === -1?6: formatIndex].symbol; }

加上上面的答案,这将给出1000的1k而不是1.0k

function kFormatter(num) {
    return num > 999 ? num % 1000 === 0 ? (num/1000).toFixed(0) + 'k' : (num/1000).toFixed(1) + 'k' : num
}

韦伦·弗林解决方案的2020版。

const SI_SYMBOLS = ["", "k", "M", "G", "T", "P", "E"];

const abbreviateNumber = (number, minDigits, maxDigits) => {
    if (number === 0) return number;

    // determines SI symbol
    const tier = Math.floor(Math.log10(Math.abs(number)) / 3);

    // get suffix and determine scale
    const suffix = SI_SYMBOLS[tier];
    const scale = 10 ** (tier * 3);

    // scale the number
    const scaled = number / scale;

    // format number and add suffix
    return scaled.toLocaleString(undefined, {
        minimumFractionDigits: minDigits,
        maximumFractionDigits: maxDigits,
    }) + suffix;
};

Tests and examples: const abbreviateNumberFactory = (symbols) => ( (number, minDigits, maxDigits) => { if (number === 0) return number; // determines SI symbol const tier = Math.floor(Math.log10(Math.abs(number)) / 3); // get suffix and determine scale const suffix = symbols[tier]; const scale = 10 ** (tier * 3); // scale the number const scaled = number / scale; // format number and add suffix return scaled.toLocaleString(undefined, { minimumFractionDigits: minDigits, maximumFractionDigits: maxDigits, }) + suffix; } ); const SI_SYMBOLS = ["", "k", "M", "G", "T", "P", "E"]; const SHORT_SYMBOLS = ["", "K", "M", "B", "T", "Q"]; const LONG_SYMBOLS = ["", " thousand", " million", " billion", " trillion", " quadrillion"]; const abbreviateNumberSI = abbreviateNumberFactory(SI_SYMBOLS); const abbreviateNumberShort = abbreviateNumberFactory(SHORT_SYMBOLS); const abbreviateNumberLong = abbreviateNumberFactory(LONG_SYMBOLS); const tests = [1e5, -9e7, [1009999.999, 2], [245345235.34513, 1, 1], [-72773144123, 3] ]; const functions = { abbreviateNumberSI, abbreviateNumberShort, abbreviateNumberLong, }; tests.forEach((test) => { const testValue = Array.isArray(test) ? test : [test]; Object.entries(functions).forEach(([key, func]) => { console.log(`${key}(${testValue.join(', ')}) = ${func(...testValue)}`); }); });