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


当前回答

一个简短的替代方案:

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

其他回答

一个简短的替代方案:

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

function AmountConveter(amount) {
  return Math.abs(amount) > 999
    ? Math.sign(amount) * (Math.abs(amount) / 1000).toFixed(1) + "k"
    : Math.sign(amount) * Math.abs(amount);
}

console.log(AmountConveter(1200)); // 1.2k
console.log(AmountConveter(-1200)); // -1.2k
console.log(AmountConveter(900)); // 900
console.log(AmountConveter(-900)); // -900

进一步改进@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"

我想出了一个非常编码的高尔夫球,它非常短!

var beautify=n=>((Math.log10(n)/3|0)==0)?n:Number((n/Math.pow(10,(Math.log10(n)/3|0)*3)).toFixed(1))+[“”,“K”,“M”,“B”,“T”,][Math.log10(n)/3|0]; 控制台.log(美化(1000)) 控制台.log(美化(10000000))

以下是我对韦伦·弗林的回答的看法。这将删除.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;
  }