1,105,578 Community Members

Java calculations are wrong! very weird!

Member Avatar
binoman
Newbie Poster
3 posts since Sep 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I just try to calculate 5.3 - 5, and the answer is a bit off.

this is the code:

double answer = 5.3 - 5;
println("answer = " + answer);

and the output is: "answer = 0.2999999999999998" instead of 0.3.

I use Eclipse on win 7 32 bit as a compiler and editor.
Any idea why this is happening and how to fix this?

tnx!

Member Avatar
Majestics
Practically a Master Poster
694 posts since Jul 2007
Reputation Points: 84 [?]
Q&As Helped to Solve: 66 [?]
Skill Endorsements: 6 [?]
 
0
 

Use Round Function if u want to round the data
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html#round%28double%29

You can also format double to 2 digits by DecimalFormat class in java...
http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html

Member Avatar
binoman
Newbie Poster
3 posts since Sep 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

This is very useful. Many thanks! I'll use that, and most likely it will solve the issue, but do you know why it happened in the first place?

Member Avatar
Bladtman242
Junior Poster
185 posts since Dec 2008
Reputation Points: 8 [?]
Q&As Helped to Solve: 4 [?]
Skill Endorsements: 0 [?]
 
0
 

I am absolutely not an expert at this, but I think this might answer your question.

(Link was provides to me by SasseMan some time ago)

Member Avatar
JamesCherrill
... trying to help
10,415 posts since Apr 2008
Reputation Points: 2,094 [?]
Q&As Helped to Solve: 1,756 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
0
 

Floating point numbers are represented in binary fractions. (1/2 + 1/4 + 1/8 + 1/16 etc). You fractional value is 0.3, ie 3/10. There is no exact way to represent 3/10 using only binary fractions, so the answer has to be slightly wrong. This is true of all floating point arithmetic on all binary computers.
When using floating point you must always be aware of this, and be ready to round your output to the right number of decimal places when you print it.

Member Avatar
binoman
Newbie Poster
3 posts since Sep 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thank you very much every one!
and thanks for answering so fast!
it help a lot!

Question Answered as of 2 Years Ago by JamesCherrill, Bladtman242 and Majestics
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: