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

时间:2018-09-06 07:42:11

标签: javascript math tofixed

在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实现呢?

3 个答案:

答案 0 :(得分:0)

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,
]));

答案 1 :(得分:-1)

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

System.Text.Encoding.GetEncoding(1250).GetString(Encoding.ASCII.GetBytes("ŠšĆ掞ČčĐđ")

每增加一个精度,小数点后一位。

答案 2 :(得分:-1)

对于那些不喜欢parseInt的人:

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

我们的想法是,将要舍入的数字减少0.001(对于toFixed(2))

但是我为更通用的用途编写了该函数,因此看起来似乎很复杂。 如果只想用于.toFixed(2),则customRound可以写为:

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