views:

81

answers:

5

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?

+3  A: 

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.

Greg Hewgill
+1  A: 

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.

eljenso
I need to use it for an finance related application
Raju
Go with BigDecimal, as suggested in other answers.
eljenso
+1  A: 

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.

Stephen C
+1  A: 

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.

PeterMmm
A: 

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.

John
you will get downvoted for "simply adding and subtracting balances you'd be fine".. this is sooo not true.
Ryan Fernandes
If you have objective reasons this is wrong please _post_ rather than make unsubstantiated criticism.
John