Vanilla javascript 函数四舍五入到最接近的百位或 100K,加上符号

Vanilla javascript function to round to nearest hundred or 100K, plus symbol

我正在尝试编写一个(vanilla javascript)函数来将数字数组舍入到最接近的 100(如果超过一千),如果超过一百万则最接近 100K,然后截断和一个符号。所以像这样的数组...

[ 1158298, 949000, 1493, 51232, 12501, 8426 ]

...会 return 这个:

1.2M, 950K, 1.5K, 51K, 13K, 8.5K

此解决方案适用于数百万个实例,但感觉非常复杂并且无法处理所有实例。我可以使用 if/else 并编写三个版本,但似乎有更优雅的解决方案?

function round(num){
  var roundNum = (Math.round(((num/100000).toFixed(2))) * .1).toFixed(1) + "M"
  return roundNum
}
console.log(round(1158298));

你可以用10的对数来求出位置。然后除以 3 得到正确的后缀。

function fn(v) {
    var p = Math.floor(Math.log(v) / Math.LN10),
        l = Math.floor(p / 3);
    return (Math.pow(10, p - l * 3) * +(v / Math.pow(10, p)).toFixed(1)) + ' ' + ['', 'K', 'M'][l];
}

var data = [1158298, 949000, 1493, 51232, 12501, 8426];

console.log(data.map(fn));