0

I'm currently in the process of learning Java. I have just run the following line in Eclipse in Win7 using jre1.8.0_25:

System.out.println(4.5 * 7.9);

The console output is: 35.550000000000004

I'm just wondering why the output is wrong.

4
  • You should read up on int, double and float precision points Commented Jan 30, 2015 at 0:26
  • 2
    Welcome to floating point arithmetic! docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html Commented Jan 30, 2015 at 0:28
  • This is normal floating point behavior. If you need precision use BigDecimal. Commented Jan 30, 2015 at 0:28
  • possible duplicate: (floating point numbers) stackoverflow.com/q/322749/2777098 Commented Jan 30, 2015 at 0:28

3 Answers 3

1

When looking for accuracy, doubles are not the best choice, as they are actually not as perfect as they may seem due to some limitations in their design.

See http://introcs.cs.princeton.edu/java/91float/

Sign up to request clarification or add additional context in comments.

Comments

1

It's not only a Java issue (feature?), it's a common issue for all languages with floating point arithmetics. It's based on IEEE 754 standard, in case you're interested.

Comments

1

It's because of loss of precision due to operations made by the computer in binary. You can see an explanation of it here.

1 Comment

It's also because of imprecision in the input literals. 7.9 cannot be represented accurately in floating-point.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.