Suppose I have a decimal value in Java that represents money.
What's the best way to round these values?
For example, if I have a value that's calculated based on a tax rate and I end up with a result of, say, 5.3999999999999995 as the tax amount, should I round it to 2 decimal places simply by doing this:
double d = 5.3999999999999995
BigDecimal bd = new BigDecimal(d).setScale(2, RoundingMode.HALF_EVEN);
d = bd.doubleValue();
to produce the currency value:
5.40
Most applications that calculate money don't use floating point (double, float); they use integer amounts representing a smaller unit.
For example in USD ($), money can be represented in cents (¢) which is 1/100 of a dollar. Or, mills (₥), a thousandth of a dollar, for some transactions.
For better accuracy, you may want to have an integer represent 1E-03 ("milli-dollars") or 1E-06. This depends on issues such as interest calculations and your level of precision.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With