0

When i review official oracle java tutorial about variables datatypes
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

I surprised when i read that
Java double data type should never be used for precise values, such as currency !

Can any one help us why?
And what is the best practice to be used for precise values, such as currency?

Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88

3 Answers3

2

Best data type for amount fields is BigDecimal. Even Joshua Bloch explains in his article in Effective Java as to why it should be used for accurate precision.

Vishal
  • 549
  • 3
  • 13
  • Agree. double itself is floating point data type, so it could lost value in effect of it operates. – P_M May 28 '16 at 15:02
1

It depends on your application. For financial applications it is often better to use decimal (although I really don't see the benefit, for example, in applications involving currency exchange rates - very precise decimal numbers in one currency are not so in the other).

For scientific and engineering applications always use double (or long double if java has such a thing). The difference between the two is more the fact that one uses base 10 and the other base 2, not so much the degree of precision. Scientist and engineers never ever care or cared about "decimal" - that only came from bankers and such.

0

Double and float types are inherently imprecise and this is termed 'floating point imprecision'.This is something you'll encounter with most programming languages, some offer a specific monetary type in an effort to overcome this possible. See http://floating-point-gui.de/ for some good info.

A common strategy is to use the int type and multiply/divide by 100 as necessary.

grae22
  • 104
  • 11
  • Can you please clarify... in what way is double type imprecise - in a way that decimal is not also imprecise? The difference is that 0.1 cannot be represented exactly in binary (which is what double is). Well, 1/3 cannot be represented exactly in decimal, either. So decimal is better if you care about dividing by 10, more than you care about dividing by 3. What other differences are there? –  May 28 '16 at 15:05