Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating point number representation, Java example [duplicate]

Could you please explain, why I got next result:

when I run this:

System.out.println((0.2 - 0.1));

I got: 0.1

when I run this:

System.out.println((0.3 - 0.2));

I got: 0.09999999999999998

I know that number "0.1" doesn't have finite representation in binary, but it doesn't explain the results above. Most likely this is not about particular language but about how digits are stored in computer.

like image 541
XZen Avatar asked Apr 16 '26 03:04

XZen


1 Answers

Java uses IEEE floating point to represent double values. It is not a precise representation, and some calculations result in tiny errors that manifest themselves in this way.

like image 66
Bohemian Avatar answered Apr 18 '26 16:04

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!