Calculating the remainder of two doubles in java

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 the remainder = 0.09999999999999906

Any idea why?

I basically need to check that x is completely divisible by y. Can you suggest alternative ways to do this in java.

thanks

+4
source share
4 answers

Due to the way floating point numbers are represented.

If you need exact values, use BigDecimal :

 BigDecimal remainder = BigDecimal.valueOf(x).remainder(BigDecimal.valueOf(y)); 

Another way to do this is to pluralize the values โ€‹โ€‹by 10 (or 100, 1000) other than int , and then use % .

+10
source

You need to compare the result that allows you to make a rounding error.

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

Also, do not use Double if you want to use double

+3
source

This post should help you. This explains why you see this behavior, and also discusses the BigDecimal class.

+1
source

Expecting accurate results from double arithmetic is problematic on computers. The main culprit is that we humans usually use base 10, while computers usually store numbers in base 2. There are problems with the conversion between them.

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); } 
+1
source

Source: https://habr.com/ru/post/1346738/


All Articles