Lost data when dividing the float by 1000

I hava float

float data = 24931192; 

When I divide it by 1000

 data = data / 1000; 

he will return for me 24931.191. Can someone tell me why? and how can i prevent this? thank you

+4
source share
4 answers

Floats / floating point numbers have only this precision (23 bits of precision in Java, to be exact), and you run into a problem when this precision is not enough. Try using doubles if the floats are not enough, although they may eventually run into problems.

+5
source

Floats have limited accuracy. Here you can learn more about how the floats are encoded: http://en.wikipedia.org/wiki/IEEE_floating-point_standard

If you need precision, you should use BigDecimal: http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html

+3
source

Floating-point data types do not have infinite precision, so you will see such small quirks. One option (if you really want to get a floating-point result) is to perform the operation with double precision, and then apply to the float. Another option is to use something like BigDecimal, not a float.

+1
source

Floating point values ​​( float and double ) are approximate. You can see rounding errors, and it is actually not possible to accurately represent some values. Think about 1/3 = 0.333333... : In the end, the slots for storing bits run out, and you get "(1/3) * 3 = 0.999999 ..."

In most cases, precise answers are not required to require more than double . If so, check out BigDecimal , which is much slower.

+1
source

Source: https://habr.com/ru/post/1495666/


All Articles