如何更改 JavaScript 中的四舍五入规则?

How can I change rules of rounding numbers in JavaScript?

在JavaScript中使用toFixed(2)方法的结果如下:

3,123 = 3,12
3,124 = 3,12
3,125 = 3,13
3,126 = 3,13 

这当然是对的,但我想更改逗号后出现5个数字时四舍五入(增加)数字的规则。所以我想要以下结果:

3,123 = 3,12
3,124 = 3,12
**3,125 = 3,12** (don't increase the number)
3,126 = 3,13

如何在 JavaScript 中实现此目的?

您可以为此使用基础数学和解析:

parseInt(number * 100, 10) / 100; //10 param is optional

每个精度加一位小数。

function customRoundUp(numbers) {
  // Stringify the numbers so we can work on the strings
  const stringified = numbers.map(x => x.toString());

  return stringified.map((x) => {
    // Look if we match your special case of 5
    // If we don't, use the regular toFixed()
    if (x[x.length - 1] !== '5') {
      return parseFloat(x).toFixed(2);
    }

    // If we do, remove the 5 from the equation and round it up
    // So it will round it up low instead of high
    return parseFloat(x.substring(0, x.length - 1)).toFixed(2);
  });
}

const numbers = [
  3.123,
  3.124,
  3.125,
  3.126,
];

console.log(customRoundUp(numbers));


重构后的版本

function customRoundUp(numbers) {
  return numbers.map((x) => {
    const str = String(x);
    
    if (str[str.length - 1] !== '5') return x.toFixed(2);
    
    return parseFloat(str.substring(0, str.length - 1)).toFixed(2);
  });
}

console.log(customRoundUp([
  3.123,
  3.124,
  3.125,
  3.126,
]));

对于那些不喜欢 parseInt 的人:

function customRound(number, numDecimal)
{
    var x = number - 1/Math.pow(10, numDecimal + 1);
    return x.toFixed(numDecimal);
}

想法是,将要舍入的数字减少 0.001(在 toFixed(2) 的情况下)

但是我写的函数是为了更通用的用途,所以看起来很复杂。 如果你只想使用 for .toFixed(2),那么 customRound 可以这样写:

function customRound(number)
{
    var x = number - 0.001;
    return x.toFixed(2);
}