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

江枫思渺然 提交于 2019-12-18 04:54:38

问题


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 for few cases.

Suppose that toFixed(2) is applied for value 17.525 then it gives the result 17.52, And if it is applied for 5.525 then it gives the result 5.53.

In the later case the rounding result is accurate, so can you please suggest what needs to be done to get the accurate rounding result as in the later case. Or can you please suggest an alternative to this toFixed function to get correct rounding results?


回答1:


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.




回答2:


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




回答3:


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).



来源:https://stackoverflow.com/questions/10768083/tofixed2-rounds-x-525-inconsistently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!