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

前端 未结 4 462
半阙折子戏
半阙折子戏 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

    0 讨论(0)
  • 2020-12-06 14:04

    Floating point inaccuracy means that most numbers ending .525 are actually .52500..1, and others are .5249999.....

    Which way the value rounds depends on whether the closest actual representation in IEEE-754 floating point is above or below the desired value.

    0 讨论(0)
  • 2020-12-06 14:15

    Instead of toFixed() use Math.ceil() , Math.floor() or Math.round()

    with a way around like

    var rnum = 5.525,
        decimalPlaces = 2,
        factor = Math.pow(10, decimalPlaces),
        newnumber = Math.round(rnum * factor) / factor,
        mydecimalvalue = parseFloat(newnumber); 
    

    the result is 5.53

    0 讨论(0)
  • 2020-12-06 14:21

    Convert the number to String and work with it?

    That is the last resort after I have tried to use Math.round, or simulate the nearest rounding with Math.ceil, but failed. When multiplying with 100, some number (such as 17.525) will be a bit less than 100 times its value (1752.5), while other numbers (such as 17.545) will be a bit more than 100 times its value (1754.5).

    0 讨论(0)
提交回复
热议问题