toFixed(2) rounds “x.525” inconsistently?

前端 未结 4 464
半阙折子戏
半阙折子戏 2020-12-06 13:20

I\'m experiencing rounding errors when using toFixed:

I used toFixed(2) on my numeric value calculations, but the rounding results are not as expected

4条回答
  •  爱一瞬间的悲伤
    2020-12-06 14:02

    Use Intl.NumberFormat and in options set minimumFractionDigits and maximumFractionDigits to the same number (number of digits you want to display).

    const formatter = [0, 1, 2, 3, 4, 5].map(
        (decimals) =>
            new Intl.NumberFormat('en-US', {
                minimumFractionDigits: decimals,
                maximumFractionDigits: decimals,
            }),
    );
    
    console.log(formatter[2].format(17.525)); // 17.53
    console.log(formatter[2].format(5.525)); // 5.53
    console.log(formatter[2].format(1.005)); // 1.01
    console.log(formatter[2].format(8.635)); // 8.64
    console.log(formatter[2].format(8.575)); // 8.58
    console.log(formatter[2].format(35.855)); // 35.86
    console.log(formatter[2].format(859.385)); // 589.39
    console.log(formatter[2].format(859.3844)); // 589.38
    console.log(formatter[2].format(.004)); // 0.00
    console.log(formatter[2].format(0.0000001)); // 0.00
    
    // keep in mind that this will not be formatted as expected, as the value that
    // you pass is actually 0.07499999999998863. 
    console.log(formatter[2].format(239.575 - 239.5)); // 0.07
    console.log(formatter[2].format(0.07499999999998863)); // 0.07

提交回复
热议问题