Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 403
Ahsan Abid Avatar asked Nov 21 '11 08:11

Ahsan Abid


People also ask

What data type should be used for currency in Java?

1 Answer. Java has Currency class that represents the ISO 4217 currency codes. BigDecimal is the best type for representing currency decimal values.

What is rounding mode in Java?

Specifies a rounding behavior for numerical operations capable of discarding precision. Each rounding mode indicates how the least significant returned digit of a rounded result is to be calculated.

What is rounding mode in Bigdecimals Java?

The enum RoundingMode provides eight rounding modes: CEILING – rounds towards positive infinity. FLOOR – rounds towards negative infinity. UP – rounds away from zero. DOWN – rounds towards zero.


1 Answers

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.

like image 140
Aaron Digulla Avatar answered Sep 28 '22 17:09

Aaron Digulla