0

在 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 中实现这一点?

4

3 回答 3

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

于 2018-09-06T07:50:29.353 回答
-1

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

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

对于每个精度,添加一个小数步长。

于 2018-09-06T07:45:48.993 回答
-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);
}
于 2018-09-06T08:48:21.557 回答