Should we use double or BigDecimal for calculations in Java?
How much is the overhead in terms of performance for BigDecimal as compared to double?
Should we use double or BigDecimal for calculations in Java?
How much is the overhead in terms of performance for BigDecimal as compared to double?
For general floating point calculations, you should use double
. If you are absolutely sure that you really do need arbitrary precision arithmetic (most applications don't), then you can consider BigDecimal
.
You will find that double
will significantly outperform BigDecimal
(not to mention being easier to work with) for any application where double
is sufficient precision.
Update: You commented on another answer that you want to use this for a finance related application. This is one of the areas where you actually should consider using BigDecimal
, otherwise you may get unexpected rounding effects from double
calculations. Also, double
values have limited precision, and you won't be able to accurately keep track of pennies at the same time as millions of dollars.
As always: it depends.
If you need the precision (even for "small" numbers, when representing amounts for example) go with BigDecimal
.
In some scientific applications, double
may be a better choice.
How much is the overhead in terms of performance for BigDecimal as compared to double?
A lot. For example, a multiplication of two doubles is a single machine instruction. Multiplying two BigDecimals is probably a minimum of 50 machine instructions, and has complexity of O(N * M)
where M
and N
are the number of bytes used to represent the two numbers.
For a serious financial application BigDecimal is a must.
Depends on how many digits you need you can go with a long and a decimal factor for visualization.
Even in finance we can't answer without knowing what area. For instance if you were doing currency conversions of $billions, where the conversion rate could be to 5 d.p. you might have problems with double. Whereas for simply adding and subtracting balances you'd be fine.
If you don't need to work in fractions of a cent/penny, maybe an integral type might be more appropriate, again it depends on the size of numbers involved.