programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Bear Bibeault
• Devaka Cooray
• Liutauras Vilda
• Jeanne Boyarsky
Sheriffs:
• Knute Snortum
• Junilu Lacar
• paul wheaton
Saloon Keepers:
• Ganesh Patekar
• Frits Walraven
• Tim Moores
• Ron McLeod
• Carey Brown
Bartenders:
• Stephan van Hulst
• salvin francis
• Tim Holloway

# double or BigDecimal

Ranch Hand
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.

Ranch Hand
Posts: 357
exactly if your calculations are monetary calculations it would be better to use a BigDecimal instead of double ;)

(peace)

Marshal
Posts: 61691
193
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
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
Marshal
Posts: 61691
193
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.