Floating point number representation, Java example [duplicate]

南笙酒味 提交于 2019-12-01 08:12:01

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!