R
Rick DeBay
I'm doing some simple currency calculations (US, non-fractional pennies) and the
code I inherited is using floats. It turns out the rounding is all messed up and
accounting is noticing that pennies are getting dropped.
This is actually two questions, as I notice floating point results go wild for
simple addition/subtraction if parentheses are moved (for addition/subtraction
this shouldn't matter if the sign is commuted).
How should I refactor this code? It's pretty simple, trying to split a cash
value between two accounts and rounding to the nearest cent.
I tried a float calculation with add/subtract multiple values, and then
multiplied the result (with the percentage one party was to receive),
constructed a BigDecimal, and scaled it. But when I subtracted the BigDecimal
from the total (to find what the other party was to get) the JVM used the
underlying value (with the really long decimal) instead of the scaled version.
So I still can't do a simple "you get x%, and you get the rest" and have it come
out to whole cents, without pennies left over or missing. Any tips?
Rick DeBay
code I inherited is using floats. It turns out the rounding is all messed up and
accounting is noticing that pennies are getting dropped.
This is actually two questions, as I notice floating point results go wild for
simple addition/subtraction if parentheses are moved (for addition/subtraction
this shouldn't matter if the sign is commuted).
How should I refactor this code? It's pretty simple, trying to split a cash
value between two accounts and rounding to the nearest cent.
I tried a float calculation with add/subtract multiple values, and then
multiplied the result (with the percentage one party was to receive),
constructed a BigDecimal, and scaled it. But when I subtracted the BigDecimal
from the total (to find what the other party was to get) the JVM used the
underlying value (with the really long decimal) instead of the scaled version.
So I still can't do a simple "you get x%, and you get the rest" and have it come
out to whole cents, without pennies left over or missing. Any tips?
Rick DeBay