Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lost data when divide float by 1000

Tags:

java

I hava float

float data = 24931192;

When i divide it by 1000

data = data / 1000;

it return for me 24931.191. Can anyone tell me why? and how can i prevent it? Thank you

like image 961
Long Vu Avatar asked Dec 26 '22 23:12

Long Vu


2 Answers

Floats/floating point numbers only have so much precision (23 bits of precision in Java, to be precise), and you just ran into an issue where that precision isn't quite enough. Try using doubles if floats aren't enough, though even those will run into issues eventually.

like image 67
qaphla Avatar answered Jan 14 '23 13:01

qaphla


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

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

like image 25
Akinakes Avatar answered Jan 14 '23 15:01

Akinakes