• Post Reply Bookmark Topic Watch Topic
  • New Topic

Double loosing its value..  RSS feed

 
Karthick Dharani Vidhya
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

The following piece of code

(2.05*1000000) results in 2049999. This happens for 2.01 too leaving to 2.009999.

Any idea on how to avoid this would be helpful. I tried strictfp, it gives the same as mentioned above.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Floating point numbers have finite precision, and there are some (many) numbers that can't be represented exactly. Many multiples of 0.1 are among these.

Note that the value of 2.05*1000000 is not 2049999; it's 2049999.9999999998, which is considerably closer to the exact answer. All you need to do is be careful about how you display the results of floating-point calculations. Instead of just System.out.println(number) use System.out.format() or java.text.DecimalFormat, which will let you round more intelligently. For example,

System.out.format("%.0f\n", 2.05*1000000 );

prints "2050000".
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If performance is not your primary concern you could use java.math.BigDecimal for exact representation of decimal values and high precision

this and this has more info on the subject.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!