So I was working with some modulus and I was confused as to why when I do
.3%.1
I get
0.09999999999999998
instead of 0... How do I fix this?
So I was working with some modulus and I was confused as to why when I do
.3%.1
I get
0.09999999999999998
instead of 0... How do I fix this?
Consider BigDecimal:
Immutable, arbitrary-precision signed decimal numbers.
This allows exact representation of your values. The reason why it doesn't work (as you expect) with floating point values is because they aren't exact.
So using the BigDecimal API,
BigDecimal n1 = new BigDecimal("0.3");
BigDecimal n2 = new BigDecimal("0.1");
BigDecimal r = n1.remainder(n2);
System.out.println(r);
Output:
0.0
The closest double to 0.03 is 0.0299999999999999988897769753748434595763683319091796875 and the closest double to 0.01 is 0.01000000000000000020816681711721685132943093776702880859375
Reducing something slightly less than 0.03 modulo something slightly greater than 0.01 must result in a value slightly less than 0.01.
Numbers that do not have exact floating point representations are equally likely to be represented by something slightly small or slight large. That works fine with rounding, but can give inconvenient results with floor, ceiling and similar operations, including modulo, in which values with small differences are treated very differently.
As already suggested, if exact handling of decimal fractions is especially important, use BigDecimal or scale by a power of ten and do integer arithmetic. Otherwise, please give more information on the context and reason for the modulo operation.
You can try this -:
System.out.println((int)(.3%.1));
this will print o/p
as 0
.
The reason is since you are doing floating point arithmetic the result is a floating point number.