Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

strange behavoir rounding a float number

 
marcello marangio
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all
can anyone explain this thing?



this code prints out

2.8999999

instead of

2.85
WHY???
thanks
M
 
Paul Clapham
Sheriff
Pie
Posts: 20964
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That number must be the nearest approximation you can make to the decimal number 2.9 using a float value, which is stored in binary rather than decimal form. If you're asking why you get 2.9 instead of 2.85, I invite you to display the contents of the intermediate string.
 
marcello marangio
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Clapham wrote:That number must be the nearest approximation you can make to the decimal number 2.9 using a float value, which is stored in binary rather than decimal form. If you're asking why you get 2.9 instead of 2.85, I invite you to display the contents of the intermediate string.


Hi paul, thanks for your reply.
Actually I would expect 2,9 as result, as you suggested.
I don't understand why I am getting 2.89999 instead of a rounded value of 2.9.

this can be brought back to the following result:



prints out
2.8500001

Should I switch to double instead of float?
thanks
m
 
Lester Burnham
Rancher
Posts: 1337
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
marcello marangio wrote:Should I switch to double instead of float?

That won't help. See #20 in the JavaBeginnersFaq.
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseCodeTags when posting code. It will highlight your code and make it much easier to read. It probably will also increase the number of people helping you. I'll add them for you since you are relatively new so that you can see the difference.
 
marcello marangio
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lester Burnham wrote:
marcello marangio wrote:Should I switch to double instead of float?

That won't help. See #20 in the JavaBeginnersFaq.


shame on me...
thanks a million.
M
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic