aspose file tools*
The moose likes Java in General and the fly likes double or BigDecimal Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "double or BigDecimal" Watch "double or BigDecimal" New topic
Author

double or BigDecimal

Ramna Reddy
Ranch Hand

Joined: Aug 06, 2006
Posts: 96
Hello Ranchers,
In our application,the datatype 'double' has been used for monetary transaction,now there is a calculation of adding two fares,the result is not quite correct.

For Ex: sum of 185.70 , 642.20 gives 827.9000000000001, but that is not correct, it should be only 827.90

Is this because of the datatype double?


Thank you,
ramana.
Omar Al Kababji
Ranch Hand

Joined: Jan 13, 2009
Posts: 357
exactly if your calculations are monetary calculations it would be better to use a BigDecimal instead of double ;)

(peace)


Omar Al Kababji - Electrical & Computer Engineer
[SCJP - 90% - Story] [SCWCD - 94% - Story] [SCBCD - 80% - Story] | My Blog
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38350
    
  23
Agree about BigDecimal. For that transaction try . . . new BigDecimal("185.70").add(new BigDecimal("642.20"));
Note the "" because you can get errors passing doubles to the BigDecimal constructor. Better to pass Strings instead.

We have a page of FAQs: look at no 20, which will provide much more information.

An alternative approach is to multiply all your prices by 100 and us integer arithmetic.
Ramna Reddy
Ranch Hand

Joined: Aug 06, 2006
Posts: 96
Thank you guys,

To avoid the above the problem,now I have to convert 'double ' values to BigDecimal, I would like to know,if converting double to bigdecimal and again bigdecimal to double,would result any bad effects..I mean any truncation takes place.

For Ex;
static Double getTotal(){
Double dTotal = new Double(0.0);//suppose this is existing
BigDecimal bTotal = new BigDecimal(Double.toString(dTotal));// I want to change like this

//calculation
//dTotal += anObject.getTotal(); // let's say existing as above
bTotal = bTotal.add(new BigDecimal(anObject.getTotal().toString()));// new change..here anObject.getTotal() returns double value


dTotal = bTotal.doubleValue();

return dTotal;
}
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38350
    
  23
Depends on the actual values in the BigDecimal. BigDecimal will happily support values like 123456789.10111213141516171819, which would be badly truncated if you change it to a double. I can see no point in mixing double and BigDecimal arithmetic; stick to BigDecimal, but remember you have to specify the rounding mode if you divide.
And you may not need "new BigDecimal(0.0);" there is (I think) a value ZERO in the BigDecimal class already set up.

There was more discussion about a similar problem recently, here.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: double or BigDecimal