问题
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