Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What rounding method should you use in Java for money?

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
like image 1000
Tom Currency Avatar asked Oct 24 '25 18:10

Tom Currency


1 Answers

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.

like image 158
Thomas Matthews Avatar answered Oct 27 '25 08:10

Thomas Matthews