Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating remainder of two doubles in java

Tags:

java

double

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

like image 767
Jasmine Avatar asked Apr 05 '11 13:04

Jasmine


2 Answers

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

like image 181
Bozho Avatar answered Oct 19 '22 19:10

Bozho


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

like image 30
Peter Lawrey Avatar answered Oct 19 '22 19:10

Peter Lawrey