我已经有钱abbreviater但不知道怎么做它所以它显示$ 1.05k等

时间:2017-04-22 11:51:41

标签: javascript html decimal

我做了一个闲置的点击游戏,你可以点击美元账单并获得金钱和升级等。我刚刚创建了一个abbreviateNumber函数,它缩短了1000到1k,1m,1t等值。我复制了它离开了前一个帖子:Convert long number into abbreviated string in JavaScript, with a special shortness requirement,但我不确定如何显示2个小数位而不是1个,例如1.05k,2.65M等。

如果有人可以帮助我,我会感激不尽,所以我可以继续对游戏进行编码,我的abbreviateNumber功能如下:

function abbreviateNumber(value) {
    var newValue = value;
    if (value >= 1000) {
        var suffixes = ["", "k", "m", "b","t"];
        var suffixNum = Math.floor( (""+value).length/3 );
        var shortValue = '';
        for (var precision = 2; precision >= 1; precision--) {
            shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision));
            var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');
            if (dotLessShortValue.length <= 2) { break; }
        }
        if (shortValue % 1 != 0)  shortNum = shortValue.toFixed(1);
        newValue = shortValue+suffixes[suffixNum];
    }
    return newValue;
}

2 个答案:

答案 0 :(得分:2)

您可以使用对数和.toFixed()在几行中实现此功能(您在那里的功能甚至无法正确确定数字的大小):

var suffixes = ['', 'k', 'm', 'b', 't', 'qd', 'qt', 'sx', 'sp', 'o', 'n', 'd'];
var log1000 = Math.log(1000);

function abbrevNum(num, decimalPlaces) {
  if (num < 0) { return '-' + abbrevNum(-num, decimalPlaces); }
  if (num < 1000) { return num.toFixed(decimalPlaces); }

  var magnitude = Math.min(Math.floor(Math.log(num) / log1000), suffixes.length - 1);
  var adjusted = num / Math.pow(1000, magnitude);

  return adjusted.toFixed(decimalPlaces) + (suffixes[magnitude] || '');
}

console.log(abbrevNum(1323457, 2));
console.log(abbrevNum(13357, 2));
console.log(abbrevNum(0, 2));
console.log(abbrevNum(0.456, 2));
console.log(abbrevNum(-23456, 2));
console.log(abbrevNum(7.567e20, 2));
console.log(abbrevNum(9.23456e28, 2));
console.log(abbrevNum(8.235926e37, 2));

答案 1 :(得分:-2)

您正在寻找标准的Javascript方法.toFixed

var n = 1.4
n.toFixed(2)

收益率为“1.40”。而且,虽然您没有要求审核,但该代码很邋and且难以辨认。怎么样:

const formatter = (suffix, divisor) => n => (n / divisor).toFixed(2) + suffix;
const forms = [
  n => n.toFixed(2),
  formatter("k", 1000),
  formatter("m", 1000000),
  formatter("b", 1000000000),
  formatter("t", 1000000000000),
]; 
const zeros = n => n && Math.floor(Math.log10(n) / 3);
const format = n => (n < 0) ? ("-" + format(-n)): forms[Math.min(zeros(n), forms.length-1)](n);

console.log(format(0));
console.log(format(101));
console.log(format(1010));
console.log(format(-1010));
console.log(format(1010000));
console.log(format(1010000000));
console.log(format(1010000000000));
console.log(format(1010000000000000));

在三行代码中做同样的事情。