在java中计算两个双打的余数 [英] Calculating remainder of two doubles in java
本文介绍了在java中计算两个双打的余数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
Double x = 17.0;
双y = 0.1;
double余数= x.doubleValue()%y.doubleValue();
当我运行这个我得到余数= 0.09999999999999906
任何想法为什么?
我基本上需要检查x是否完全可以被y整除。你可以在java中提出一些替代方法。
谢谢
解决方案
p>由于浮点数的表示方式。
如果您需要确切的值,请使用 BigDecimal
:
BigDecimal余数= BigDecimal.valueOf(x).remainder(BigDecimal.valueOf(y));
另一种方法是将每个值乘以10(或100,1000),转换为 int
,然后使用%
。
I have the following code :
Double x = 17.0;
Double y = 0.1;
double remainder = x.doubleValue() % y.doubleValue();
When I run this I get remainder = 0.09999999999999906
Any idea why??
I basically need to check that x is fully divisible by y. Can you suggest alternative ways to do that in java.
Thanks
解决方案
Because of how floating-point numbers are represented.
If you want exact values, use BigDecimal
:
BigDecimal remainder = BigDecimal.valueOf(x).remainder(BigDecimal.valueOf(y));
Another way to to that is to multiple each value by 10 (or 100, 1000), cast to int
, and then use %
.
这篇关于在java中计算两个双打的余数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文