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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Ron McLeod
• Paul Clapham
• Devaka Cooray
• Liutauras Vilda
Sheriffs:
• Jeanne Boyarsky
• paul wheaton
• Henry Wong
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Tim Moores
• Carey Brown
• Mikalai Zaikin
Bartenders:
• Lou Hamers
• Piet Souris
• Frits Walraven

# parseDouble problem

Ranch Hand
Posts: 67
• Number of slices to send:
Optional 'thank-you' note:
Guys,
I have parseDouble problem that only happened to certain figures, example as below where it supposed to return 689.9 but it return 689.9000000000001. Why ?
==========================
class testDouble
{
public static void main(String[] args)
{
System.out.println("Hello World!");
double dTotal = 0.0;
String s1 = "325.1";
String s2 = "364.8";
dTotal = dTotal + Double.parseDouble(s1);
dTotal = dTotal + Double.parseDouble(s2);
}
}
==========================

Ranch Hand
Posts: 52
• Number of slices to send:
Optional 'thank-you' note:
This has to do with the way floating point (float or double) numbers are stored. They are stored as powers of 2, not as decimal fractions, and it isn't always possible to convert exactly between one and the other. This means that you have to treat any floating point value as being only an approximation of the decimal number. With a double you get more accuracy than with a long, but you still get only as much accuracy as the number of bits allows.
Because of this, you should be very careful when using == to compare two floating point numbers. Rather than using "if (a == b)", you should use something like
float absdiff(float a, float b) { return (a < b ? (b - a) : (a - b); }
if (absdiff(a, b) < 0.000001) ...

cb poo
Ranch Hand
Posts: 67
• Number of slices to send:
Optional 'thank-you' note:
There is also an URL from Sun:-
http://developer.java.sun.com/developer/JDCTechTips/2003/tt0204.html#2
:-)
Thank You.

(instanceof Sidekick)
Posts: 8791
• Number of slices to send:
Optional 'thank-you' note:
Good lesson here. Remember that for all the high-powered computations we do on computers, they often suck at arithmetic. Don't agree? Find one that knows ( 1 / 3 ) * 3 == 1.
[ April 07, 2003: Message edited by: Stan James ]