需要格式化数字k(thausand)而不是m(百万)或b(十亿)数字js

时间:2017-07-18 14:20:57

标签: jquery numeraljs

我们需要格式化数字 k(千)而不是m(百万)或b(十亿),numeraljs目前正在转换所有格式



var number = 2000000; 
console.log(numeral(number).format('0a'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
&#13;
&#13;
&#13;

预期结果ID 2000K谢谢

1 个答案:

答案 0 :(得分:1)

我并不熟悉数字js,但我认为你可能需要创建一个custom format

Demo - codepen

自定义格式

numeral.register('format', 'thousands', {
regexps: {
    format: /(k)/,
    unformat: /(k)/
},
format: function(value, format, roundingFunction) {
    var space = numeral._.includes(format, ' k') ? ' ' : '',
        output;

    value = value*.001;

    format = format.replace(/\s?\k/, '');

    output = numeral._.numberToFormat(value, format, roundingFunction);

    if (numeral._.includes(output, ')')) {
        output = output.split('');

        output.splice(-1, 0, space + 'k');

        output = output.join('');
    } else {
        output = output + space + 'k';
    }

    return output;
}
});

使用格式

var number = 2000000; 
console.log(numeral(number).format('0k'));