• Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Floating point conversion

 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello all,
I am trying to convert Strings to floats and am getting incorrect results during the conversion. For example:
System.out.println(Float.parseFloat("42.44"));
will display
42.439998626708984
Can anyone tell me why this is and how I can get around it?
Thanks!
 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Jeff Wisard:
System.out.println(Float.parseFloat("42.44"));


It seems to work fine for me. I can't tell you why it doesn't work for you. If it persists, take a look at NumberFormat, and see if anything there helps.
Good luck!
 
Jeff Wisard
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't know if this will make a difference: I am using JDK1.3.1_06.
 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jeff,
Floats are, in general, approximations of number values. In some cases, like .5, the float will be exact. However many numbers can't be represented exactly after they are converted to binary representation. All your result means is that your input could only be approximated as a float.
However, when you display it, you have control over how it looks. The decimalformat class will let you trim it to just two decimal places and you will be happy with the result.
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Or round it to the level of precision that you are interested in.
 
reply
    Bookmark Topic Watch Topic
  • New Topic