This week's book giveaway is in the Design forum.We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!

# double or float

DANIELA PINES
Greenhorn
Posts: 8
What would be the best practice for currency computations? Use data type double, float, Double or Float?
Thanks.

Michael Morris
Ranch Hand
Posts: 3451
Originally posted by DANIELA PINES:
What would be the best practice for currency computations? Use data type double, float, Double or Float?
Thanks.

Well it really depends on the magnitudes. If you want to calculate the US national debt to the exact cent then you would probably use a java.math.BigDecimal which provides for arbitrary precision. For normal calculations doubles should do fine.

Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34178
340
For calculations, doubles are fine. But be careful if you need to compare two doubles. 1.00001 is not equal to 1.00 and you can get some precision differences from the computation due to the way doubles are stored.

Philip Shanks
Ranch Hand
Posts: 189
Originally posted by Jeanne Boyarsky:
For calculations, doubles are fine. But be careful if you need to compare two doubles. 1.00001 is not equal to 1.00 and you can get some precision differences from the computation due to the way doubles are stored.

To expand on what Jeanne said, if you need to compare two numbers, you are better off comparing the difference to some tolerance factor, as
if ( (d2 - d1) < 0.00001 ) ....
And since part of your question has to do with double vs. Double, you are talking about a Java primitive type vs. a wrapper class around a primitive. The underlying behavior is the same.

Ilja Preuss
author
Sheriff
Posts: 14112
Originally posted by Jeanne Boyarsky:
For calculations, doubles are fine.

Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34178
340
That article explains why you should not use floats for money. It doesn't mention the use of doubles.
I imagine that doubles would have a similar effect for really large numbers. However, I work with numbers in the billions/trillions and have not encountered any problems in calcuations.

Trond Hundstuen
Greenhorn
Posts: 3
Actually you shouldn't use float or double. A far better choice for monetary calculations is the BigDecimal class. The BigDecimal class is also what you should use if you want to round off.
Best regards,
Trond

Gaurav Mac Mathur
Ranch Hand
Posts: 47
Would further recommend to write your Own Currency class and store value in BigDecimal, and have your formatter methods and mathamatical operators in that class.
Like :

Regards