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.
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 %.
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).
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.
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
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)
You're doing floating point arithmetic. 0.1 has no exact representation as a float.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With