aspose file tools*
The moose likes Java in General and the fly likes strange behavoir rounding a float number Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "strange behavoir rounding a float number" Watch "strange behavoir rounding a float number" New topic
Author

strange behavoir rounding a float number

marcello marangio
Greenhorn

Joined: Nov 26, 2010
Posts: 8
Hi all
can anyone explain this thing?



this code prints out

2.8999999

instead of

2.85
WHY???
thanks
M
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18649
    
    8

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

Joined: Nov 26, 2010
Posts: 8
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

Joined: Oct 14, 2008
Posts: 1337
marcello marangio wrote:Should I switch to double instead of float?

That won't help. See #20 in the JavaBeginnersFaq.
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

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.


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
marcello marangio
Greenhorn

Joined: Nov 26, 2010
Posts: 8
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: strange behavoir rounding a float number