用Java解析Float的正确方法是什么

用Java解析Float的正确方法是什么

本文介绍了用Java解析Float的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到Java浮点精度的一些问题

I notice some issues with the Java float precision

       Float.parseFloat("0.0065") - 0.001  // 0.0055000000134110451
       new Float("0.027") - 0.001          // 0.02600000000700354575
       Float.valueOf("0.074") - 0.001      // 0.07399999999999999999

我不仅对Float有问题,而且对Double也有问题.

I not only have a problem with Float but also with Double.

有人可以解释幕后发生的事情吗,我们如何获得准确的数字?处理这些问题时正确的方法是什么?

Can someone explain what is happening behind the scenes, and how can we get an accurate number? What would be the right way to handle this when dealing with these issues?

推荐答案

问题很简单,就是float具有有限的精度;它不能完全代表0.0065. (当然,double也是如此:它具有更高的精度,但仍然是有限的.)

The problem is simply that float has finite precision; it cannot represent 0.0065 exactly. (The same is true of double, of course: it has greater precision, but still finite.)

另一个使上述问题更加明显的问题是0.001double而不是float,因此您的float被提升为double进行减法,当然,此时系统无法恢复double 可能最初表示的精度损失.为了解决这个问题,您可以编写:

A further problem, which makes the above problem more obvious, is that 0.001 is a double rather than a float, so your float is getting promoted to a double to perform the subtraction, and of course at that point the system has no way to recover the missing precision that a double could have represented to begin with. To address that, you would write:

float f = Float.parseFloat("0.0065") - 0.001f;

使用0.001f而不是0.001.

这篇关于用Java解析Float的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:30