Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modulo doesn't work

Tags:

java

modulo

I know this will seem like a really stupid question, but I just don't get why this isn't working. This:

 System.out.println(5 % .10);

And it's returning:

0.09999999999999973

I really have NO IDEA. I'm just learning Java, and I'm pretty good with C#, so I tried with C# to. C# seemed to return the same thing also.

like image 732
hetelek Avatar asked Sep 27 '11 00:09

hetelek


People also ask

What does modulo (%) do?

Modulo is a math operation that finds the remainder when one integer is divided by another. In writing, it is frequently abbreviated as mod, or represented by the symbol %.

Does mod by 0 cause error?

The range of values for an integer modulo operation of n is 0 to n − 1 inclusive (a mod 1 is always 0; a mod 0 is undefined, possibly resulting in a division by zero error in some programming languages).

How do you do modulo in Java?

Java Modulo OperatorIt is represented by the percentage symbol (%). It is used to determine the remainder. It requires two operands. It divides the left-hand operand by the right-hand operand and gives the remainder.


3 Answers

As others explained, this is due to inaccuracies caused by floating point precision.

You should use BigDecimal, in this case the remainder method for precise arithmetic involving decimals.

BigDecimal number = new BigDecimal(5);
BigDecimal divisor = new BigDecimal("0.1");
BigDecimal result = number.remainder(divisor);
System.out.println(result); // 0
like image 101
Charles Goodwin Avatar answered Oct 27 '22 04:10

Charles Goodwin


This is due to floating-point precision. 0.10 cannot be represented exactly in binary. Therefore the result is not exactly 0.10 and is hence not modded down to 0.

This will work with 0.25 because 0.25 can be represented exactly in binary.

EDIT:

In general, any number that can be expressed as a fraction with a power-of-two in the denominator can be expressed exactly in IEEE floating-point. (provided it doesn't over/underflow)

like image 23
Mysticial Avatar answered Oct 27 '22 04:10

Mysticial


You're doing floating point arithmetic. 0.1 has no exact representation as a float.

like image 21
Mark Byers Avatar answered Oct 27 '22 06:10

Mark Byers