This article discusses how to perform monetary operations in Java: what is the correct way of using
double and what alternatives do we have.
Monetary operations using long/double
The easiest way to represent monetary values in financial environment is to work with the smallest currency units – for example, cents in USA, instead of normal currency unit – dollar in USA.
long datatype is rather suitable for this case. Unfortunately, sometimes we have to divide such values or multiply them by decimal point values (for example, calculate how much you have earned on your savings account). This means that while we can still use
long for storing cents, we need to multiply/divide using decimal point arithmetic.
Do not use
float for any monetary operations unless you absolutely sure. It has too low precision (23 bits).
double calculations are not precise. Even simple one, such as addition and subtraction:
"362.2 - 362.6 = -0.4000000000000341". This means we should:
- Avoid working with non-integral values while using
double(calculate in the smallest currency units).
- Round any multiplication/division results using
Math.round/rint/ceil/floor(per your system requirements).