Dealing with prices and rounding in Javascript [closed]

耗尽温柔 提交于 2019-12-11 17:19:26

问题


So, as we all know, 0.1 + 0.2 is equivalent to 0.30000000000000004.

I've got an application which will be used at a point of sell to collect money, and I don't want to deal with the nightmare of floating point arithmetic. My options, as I see them, are

a) using integers and dealing with prices as Cents/Pence, doing the math there, and then dividing by 100 to get the cost in Dollars/Pounds

b) using a Decimal library to do accurate math on the numbers

I'm using react.js and webpack. Anybody with production experience have any advice? I'm leaning toward option a.


回答1:


It is an established convention to do all currency operations (and any operation that has a fixed number of decimal places for that matter) as integer operations and convert that value to decimal for display. Use a decimal library only if accuracy is vital and the number of decimal places varies from number to number.



来源:https://stackoverflow.com/questions/54903883/dealing-with-prices-and-rounding-in-javascript

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