Calculating remainder of two doubles in java

前端 未结 3 1295
独厮守ぢ
独厮守ぢ 2021-01-19 02:04

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 r

3条回答
  •  攒了一身酷
    2021-01-19 02:39

    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);
    
    }
    

提交回复
热议问题