Java - 如何避免在除法和转换为int期间丢失精度? [英] Java - How to avoid loss of precision during divide and cast to int?

查看:1371
本文介绍了Java - 如何避免在除法和转换为int期间丢失精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况需要找出一个int进入十进制的次数,但在某些情况下,我正在失去精度。以下是方法:

I have a situation where I need to find out how many times an int goes into a decimal, but in certain cases, I'm losing precision. Here is the method:

public int test(double decimalAmount, int divisor) {
  return (int) (decimalAmount/ (1d / divisor));
}

这个问题是我输入1.2作为小数和5作为除数,我得到5而不是6.我怎么能再调整这个,所以我知道5作为一个int进入十进制数的次数是多少次?

The problem with this is if I pass in 1.2 as the decimal amount and 5 as the divisor, I get 5 instead of 6. How can I restrusture this so I know how many times 5 goes into the decimal amount as an int?

推荐答案

计算结果可能类似于5.999999999994,因为浮点结果不一定是整数。当你转换为int时,你会截断,结果是5.对于另一组类似的参数,你可能会看到6.0000000000002的结果,它会给你6。

The result of the computation is likely something like 5.999999999994, as the floating-point result is not necessarily exactly an integer. When you cast to an int, you truncate, and the result is 5. For another similar set of arguments, you might see a result of 6.0000000000002, and it would give you 6.

但事实上,这对浮点表示非常敏感,这让人怀疑为什么你认为你想要这个 - 也许有更好的方法去做你想做的事情。例如,上面的答案是正确的,这简化了,然后更不清楚这是什么。

But the fact that this is so sensitive to floating-point representation calls into question why you think you want this -- maybe there's a better way to do what you wish to do. For example the answer above is correct, this simplifies, and then it's even less clear what the point is.

要真正做我认为你想做的事情,你不需要使用 double s或 float s。你需要 java.util.BigDecimal - 查看它是如何工作的。您可以使用它精确乘以5和1.2得到6。

To really do what I think you imagine you want to do, you need to not use doubles or floats. You need java.util.BigDecimal -- look up how it works. You can use it to "exactly" multiply 5 and 1.2 to get 6.

这篇关于Java - 如何避免在除法和转换为int期间丢失精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆