0

When I run the code

System.out.println(12%5)

It always, without fail, prints out 2. But, if it try this:

System.out.println(2%0.1)

It prints out 0.0999999999999999. Im trying to use the % operator to round a number down to a given interval, but if the interval is a decimal, it always glitches like this. What alternatives exist? Thanks.

EDIT: The code i'm using to round to the nearest interval is this:

value -= value%0.1;

If value were to equal 0.567, value%0.1 would be 0.067, and 0.567-0.067 = 0.5.

Java Noob
  • 351
  • 1
  • 6
  • 15
  • can you printf instead of println to format the output to a specified number of decimal places combined with the modulus operator? – B. Witter Mar 27 '17 at 14:16
  • both number first define as float, do your operation and then parse the final result or you can round the floating point number. remember in first one both are integer gives you integer, and second one automatically into float. – BetaDev Mar 27 '17 at 14:18
  • 1
    That's most likely a problem of floating point precision. You _could_ use `BigDecimal` or you could explain the exact meaning of "round a number down to a given interval" (preferably with examples). Then we might be able to suggest alterantives. 2%0.1 should result in 0, should 2.05%0.1 result in 0.05 then? – Thomas Mar 27 '17 at 14:18
  • I just printed the value into the console to test it. In reality, I'm drawing the value to a window, and that's the value it displays. – Java Noob Mar 27 '17 at 14:24

1 Answers1

0

An alternative is Math.round and/or Math.floor. If you truly want to round to the nearest interval, use Math.round( num / interval ) * interval. If you wish to round down to the next lower interval, use Math.floor( num / interval ) * interval.

See https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round(double)

schtever
  • 3,210
  • 16
  • 25