2

I have this code sample:

float approx = 1234567712f;
System.out.println(approx);

Instead of printing "1.234567712E9" or something similar it prints "1.23456768E9". As I understand, this has something to do with precision at the binary level.

How many binary digits is the precision for float numbers (before and after the comma (",") symbol)? Can you explain it in a simple way why is this happening?

Zong
6,2585 gold badges34 silver badges46 bronze badges
asked Nov 22, 2013 at 19:21
2

2 Answers 2

2

A floating point number consists of a "significand" and an "exponent". To represent integers down to the last odd digit, the exponent would have to be zero. This means that you have 24 bits available (the 24th bit is always 1 and therefore not stored), and the largest integer you can store is

0xFFFFFF == 16777215

When you want to add 2 to this number, the "accurate" representation would be

0x1000001 = 16777217

You would need 25 bits to store this number; so the last digit gets lopped off, and the number will be stored as

0x800000 x 2^1 == 16777216

As numbers get larger, the "jump" between successive representable numbers gets bigger. By the time you get to

1234567112 == 0x4995FFC8

You would need 32 bits to store it. But you only have 24 bits, so it will be stored internally as something like

0x499600 x 2^8 (rounded to the closest number).

= 0x49960000 = 1234567168

which is the number you saw.

answered Nov 22, 2013 at 19:39
Sign up to request clarification or add additional context in comments.

Comments

0

float has a precision up to 7 digits before and after the comma. That's why 1234567 is correct and the other 3 digits aren't. You should use double instead of float if you want to calculate with high numbers

answered Nov 22, 2013 at 19:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.