user1574866
user1574866

Reputation: 275

Big float numbers weird results

In java I am using float to store the numbers. I chose the float format as I am working both with integers and double numbers, where the numbers are different, there can be big integers or big double numbers with different number of decimals. But when I insert these numbers into database, the wrong number is stored. For example:

float value = 0f; value = 67522665; System.out.println(value);

Printed: 6.7522664E7 and it is stored in the database as 67522664 not as 67522665

Upvotes: 3

Views: 9675

Answers (3)

Campa
Campa

Reputation: 4495

As far as I got it, this is about the gap size (or ULP, units in the last place) in the binary representation, that is the spacing between contiguous f-point values.

This value is equal to:

2^(e+1-p)

being e the actual exponent of a number, and p the precision.

Note that the spacing (or gap) increases as the value of the represented number increases:

enter image description here

In IEEE-754, the precision is p 24, so you can see that when e >= 23 we can start talking of integer spacing in the floating point world.

2^23 = 8388608   --> 8388608 actually stored IEEE-754
       8388608.2 --> 8388608 actually stored IEEE-754

Things get worse as numbers get bigger. For example:

164415560 --> 164415552 actually stored IEEE-754

Ref: The Spacing of Binary Floating-Point Numbers

Upvotes: 0

renz
renz

Reputation: 1070

Doubles and floats have storage issues. How is floating point stored?

"The float and double types are designed primarily for scientific and engineering calculations. They perform binary floating-point arithmetic, which was carefully designed to furnish accurate approximations quickly over a broad range of magnitudes. They do not, however, provide exact results and should not be used where exact results are required."

Don't use float. Use BigDecimal instead. And in my experience with databases, they return their NUMBER-typed elements as BigDecimal. When I fetch them using JDBC, they are BigDecimal objects.

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

Floating point numbers have limited resolution — roughly 7 significant digits. You are seeing round-off error. You can use a double for more resolution or, for exact arithmetic, use BigDecimal.

Suggested reading: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Upvotes: 8

Related Questions