-1

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?

TMKang
  • 11
  • 1

3 Answers3

0

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
jdphenix
  • 15,022
  • 3
  • 41
  • 74
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.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
-1

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.

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
  • This doesn't answer the question. The OP wants floating-point modulus. Casting it to int like you and the result won't be correct anymore. 2.0 % 1.1 = 0.9 but casting to int will result in 0 which is far from correct – phuclv Feb 03 '15 at 12:43
  • Moreover in this case it's 0 simply by luck. The remainder for division by 0.1 is **always** less than 0.1 which result in 0 when cast to int. Therefore the result is always 0 and the modulus is meaningless. The same to any number less than 1 – phuclv Feb 03 '15 at 12:46