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


当前回答

支持负数 检查!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

其他回答

韦伦·弗林解决方案的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)}`); }); });

直接的方法具有最好的可读性,并且使用最少的内存。不需要过多地使用regex、map对象、Math对象、for-loops等。

使用K格式化现金值

const formatCash = n => { 如果(n < 1e3)返回n; if (n >= 1e3) return +(n / 1e3).toFixed(1) +“K”; }; console.log (formatCash (2500));

使用K M B T格式化现金值

const formatCash = n => { 如果(n < 1e3)返回n; 如果1 e3 & & n (n > = < 1 e6)返回+ (n / 1 e3) .toFixed(1) +“K”; 如果1 e6 & & n (n > = < 1 e9) + 1 (n / e6)返回.toFixed(1) +“M”; if (n >= 1e9 && n < 1e12) return +(n / 1e9).toFixed(1) + "B"; if (n >= 1e12) return +(n / 1e12).toFixed(1) + "T"; }; console.log (formatCash (1235000));

使用负数

let format;
const number = -1235000;

if (number < 0) {
  format = '-' + formatCash(-1 * number);
} else {
  format = formatCash(number);
}

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

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

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 }

我用的是这个函数。它适用于php和javascript。

    /**
     * @param $n
     * @return string
     * Use to convert large positive numbers in to short form like 1K+, 100K+, 199K+, 1M+, 10M+, 1B+ etc
     */
 function num_format($n) {
        $n_format = null;
        $suffix = null;
        if ($n > 0 && $n < 1000) {
           $n_format = Math.floor($n);   
            $suffix = '';
        }
        else if ($n == 1000) {
            $n_format = Math.floor($n / 1000);   //For PHP only use floor function insted of Math.floor()
            $suffix = 'K';
        }
        else if ($n > 1000 && $n < 1000000) {
            $n_format = Math.floor($n / 1000);
            $suffix = 'K+';
        } else if ($n == 1000000) {
            $n_format = Math.floor($n / 1000000);
            $suffix = 'M';
        } else if ($n > 1000000 && $n < 1000000000) {
            $n_format = Math.floor($n / 1000000);
            $suffix = 'M+';
        } else if ($n == 1000000000) {
            $n_format = Math.floor($n / 1000000000);
            $suffix = 'B';
        } else if ($n > 1000000000 && $n < 1000000000000) {
            $n_format = Math.floor($n / 1000000000);
            $suffix = 'B+';
        } else if ($n == 1000000000000) {
            $n_format = Math.floor($n / 1000000000000);
            $suffix = 'T';
        } else if ($n >= 1000000000000) {
            $n_format = Math.floor($n / 1000000000000);
            $suffix = 'T+';
        }


       /***** For PHP  ******/
       //  return !empty($n_format . $suffix) ? $n_format . $suffix : 0;

       /***** For Javascript ******/
        return ($n_format + $suffix).length > 0 ? $n_format + $suffix : 0;
    }