Which rounding mode to be used for currency manipulation in java?

Ahsan Abid picture Ahsan Abid · Nov 21, 2011 · Viewed 50.3k times · Source

I have read on java site to use BigDecimal for currencies. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

But what rounding mode we should use with? which is the most appropriate one and most widely us

Answer

Aaron Digulla picture Aaron Digulla · Nov 21, 2011

There is no "correct" mode, it depends on the business case. Examples:

  • When calculating annual taxes, the fractions are often cut off (RoundingMode.FLOOR).
  • When calculating a bonus, you might want to always round in favor of the customer (RoundingMode.CEILING).
  • For taxes on a bill, you usually round HALF_UP
  • When doing complex financial simulations, you don't want to round at all.

The documentation of RoundingMode contains a lot of examples how the different modes work.

To get a better answer, you must tell us what you want to achieve.

That said, BigDecimal is the correct type to use in Java because it can preserve any amount of precision plus it lets you chose the rounding mode most suitable for your case.