Calculating remainder of two doubles in java

2019-02-22 18:07发布

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

标签: java double
4条回答
乱世女痞
2楼-- · 2019-02-22 18:48

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 %.

查看更多
叼着烟拽天下
3楼-- · 2019-02-22 18:48

You need to compare your result which allows for rounding error.

if (remainder < ERROR || remainder > 0.1 - ERROR)

Also, don't use Double when you mean to use double

查看更多
放我归山
4楼-- · 2019-02-22 18:51

This post should help you out. It explains why you are seeing this behaviour and also discusses the BigDecimal class.

查看更多
beautiful°
5楼-- · 2019-02-22 18:53

Expecting precise results from double arithmetic is problematic on computers. The basic culprit is that us humans use base 10 mostly, whereas computers normally store numbers in base 2. There are conversion problems between the two.

This code will do what you want:

public static void main(String[] args) {
    BigDecimal x = BigDecimal.valueOf(17.0);
    BigDecimal y = BigDecimal.valueOf(0.1);

    BigDecimal remainder = x.remainder(y);
    System.out.println("remainder = " + remainder);

    final boolean divisible = remainder.equals(BigDecimal.valueOf(0.0));
    System.out.println("divisible = " + divisible);

}
查看更多
登录 后发表回答