Floating point number representation, Java example

2020-03-26 05:34发布

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.

2条回答
虎瘦雄心在
2楼-- · 2020-03-26 05:58

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.

查看更多
做自己的国王
3楼-- · 2020-03-26 05:58

I agree with Bohemian above (float and double is not precise) so you will get oddities like this

but there is a solution for your problem:

NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(1);
nf.format(0.3f - 0.2f);

This will produce 0.1.

查看更多
登录 后发表回答