四舍五入到特定数字

Round to specific number

我正在寻找基本上可以做到这一点的标准 JS 方法:

iRoundTo1 = Math.abs(1000000 - myValue);
iRoundTo2 = Math.abs(2000000 - myValue);
iRoundTo5 = Math.abs(5000000 - myValue);

myValue = Math.min(iRoundTo1, iRoundTo2,
        iRoundTo5);

if (myValue === iRoundTo1) {
    myValue = 1000000;
} else if (myValue === iRoundTo2) {
    myValue = 2000000;
} else if (myValue === iRoundTo5) {
    myValue = 5000000;
}

如标题中所述,我希望我的值四舍五入为特定数字,即 1M、2M 和 5M。

不确定这是否是您想要的,但这是我的建议:

const temp = Math.abs(myValue / 1000000) * 1000000;

If 基本上会将绝对值四舍五入到最接近的 "million".

您可以根据情况添加ifswitch 语句将其转换为预定义的值。这将减少您的函数中所需的样板文件。

这里是你想要的代码。

function formatMoney(n, c, d, t) {
  var c = isNaN(c = Math.abs(c)) ? 2 : c,
    d = d == undefined ? "." : d,
    t = t == undefined ? "," : t,
    s = n < 0 ? "-" : "",
    i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))),
    j = (j = i.length) > 3 ? j % 3 : 0;

  return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function numShort(value){
    if(value < 1000000){
      return formatMoney(value, 2, ".", ",");
    }else if(value < 1000000000){
      return formatMoney((value/1000000), 2, ".", ",")+'m';
    }else{
      return formatMoney((value/1000000000), 2, ".", ",")+'b';
    }
}

console.log(numShort(100));
console.log(numShort(1000));
console.log(numShort(10000));
console.log(numShort(100000));
console.log(numShort(1000000));
console.log(numShort(10000000));
console.log(numShort(100000000));
console.log(numShort(1000000000));
console.log(numShort(10000000000));
console.log(numShort(100000000000));

当然你必须自己实现这种特殊的东西。 如果您只是想要一些奇特的单行解决方案来使您的代码更清晰:

var myValue = 1234567;
var rounded = [1000000,2000000,5000000].reduce((y,x)=>{return y.diff == undefined || Math.abs(x-myValue) < y.diff ? {val:x,diff:Math.abs(x-myValue)} : y},{}).val;
console.log(rounded);

或者您可以只声明一个函数,使其更加简洁。