Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double vs. BigDecimal?

I have to calculate some floating point variables and my colleague suggest me to use BigDecimal instead of double since it will be more precise. But I want to know what it is and how to make most out of BigDecimal?

like image 296
Truong Ha Avatar asked Aug 05 '10 09:08

Truong Ha


2 Answers

A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001) could result in the 0.001 being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen.

The disadvantage of BigDecimal is that it's slower, and it's a bit more difficult to program algorithms that way (due to + - * and / not being overloaded).

If you are dealing with money, or precision is a must, use BigDecimal. Otherwise Doubles tend to be good enough.

I do recommend reading the javadoc of BigDecimal as they do explain things better than I do here :)

like image 109
extraneon Avatar answered Sep 29 '22 07:09

extraneon


My English is not good so I'll just write a simple example here.

double a = 0.02; double b = 0.03; double c = b - a; System.out.println(c);  BigDecimal _a = new BigDecimal("0.02"); BigDecimal _b = new BigDecimal("0.03"); BigDecimal _c = _b.subtract(_a); System.out.println(_c); 

Program output:

0.009999999999999998 0.01 

Does anyone still want to use double? ;)

like image 45
Basil Avatar answered Sep 29 '22 06:09

Basil