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


当前回答

如果你喜欢,就把功劳归于韦伦·弗林

这比他处理负数和“。0”的情况。

循环和“如果”情况越少,IMO就越好。

function abbreviateNumber(number) {
    const SI_POSTFIXES = ["", "k", "M", "G", "T", "P", "E"];
    const sign = number < 0 ? '-1' : '';
    const absNumber = Math.abs(number);
    const tier = Math.log10(absNumber) / 3 | 0;
    // if zero, we don't need a prefix
    if(tier == 0) return `${absNumber}`;
    // get postfix and determine scale
    const postfix = SI_POSTFIXES[tier];
    const scale = Math.pow(10, tier * 3);
    // scale the number
    const scaled = absNumber / scale;
    const floored = Math.floor(scaled * 10) / 10;
    // format number and add postfix as suffix
    let str = floored.toFixed(1);
    // remove '.0' case
    str = (/\.0$/.test(str)) ? str.substr(0, str.length - 2) : str;
    return `${sign}${str}${postfix}`;
}

jsFiddle测试用例-> https://jsfiddle.net/qhbrz04o/9/

其他回答

一个简短的替代方案:

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; }

以下是我对韦伦·弗林的回答的看法。这将删除.0并修复当层不是整数时的未定义。

const SI_SYMBOL = ['', 'k', 'M', 'G', 'T', 'P', 'E'];

abbreviateNumber(num) {
    const tier = Math.floor(Math.log10(num) / 3) || 0;
    let result = '' + num;
    // if zero, we don't need a suffix
    if (tier > 0) {
      // get suffix and determine scale
      const suffix = SI_SYMBOL[tier];
      const scale = Math.pow(10, tier * 3);
      // scale the number
      const scaled = num / scale;
      // format number and add suffix
      result = scaled.toFixed(1).replace('.0', '') + suffix;
    }
    return result;
  }

进一步改进@Yash的回答,支持负数:

function nFormatter(num) {
    isNegative = false
    if (num < 0) {
        isNegative = true
    }
    num = Math.abs(num)
    if (num >= 1000000000) {
        formattedNumber = (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
    } else if (num >= 1000000) {
        formattedNumber =  (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
    } else  if (num >= 1000) {
        formattedNumber =  (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
    } else {
        formattedNumber = num;
    }   
    if(isNegative) { formattedNumber = '-' + formattedNumber }
    return formattedNumber;
}

nFormatter(-120000)
"-120K"
nFormatter(120000)
"120K"

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 }

支持负数 检查!isFinite 如果你想要最大单位是M,将' K M G T P E Z Y'改为' K M' 基数选项(1K = 1000 / 1K = 1024)


Number.prototype.prefix = function (precision, base) { var units = ' K M G T P E Z Y'.split(' '); if (typeof precision === 'undefined') { precision = 2; } if (typeof base === 'undefined') { base = 1000; } if (this == 0 || !isFinite(this)) { return this.toFixed(precision) + units[0]; } var power = Math.floor(Math.log(Math.abs(this)) / Math.log(base)); // Make sure not larger than max prefix power = Math.min(power, units.length - 1); return (this / Math.pow(base, power)).toFixed(precision) + units[power]; }; console.log('0 = ' + (0).prefix()) // 0.00 console.log('10000 = ' + (10000).prefix()) // 10.00K console.log('1234000 = ' + (1234000).prefix(1)) // 1.2M console.log('-10000 = ' + (-10240).prefix(1, 1024)) // -10.0K console.log('-Infinity = ' + (-Infinity).prefix()) // -Infinity console.log('NaN = ' + (NaN).prefix()) // NaN