Hanfei Sun Hanfei Sun - 2 months ago 9
Java Question

In scala, why could remainder (%) operator return a negative number?

For example,

(-3) % 2
will return
-1
instead of
1
.

What is the preferred way to get the positive remainder in Scala? Such as
(((-3) % 2) + 2) % 2
, or
abs(-3 % 2)
?

Answer

In scala, why could remainder (%) operator return a negative number?

There are different conventions for the sign of the result of a modulo operation; Wikipedia has a good article on it. Scala, like most but by no means all programming languages, has the result take the sign of the dividend (the -3 in your case).

What is the preferred way to get the positive remainder in Scala?

I doubt there's a generally-agreed preferred way; if it were me, either use Math.floorMod, which gives a result with the sign of the divisor (2 in your example) instead of the dividend (this doesn't just mean the same value as % with a different sign, see the linked JavaDoc for details). Or just an if afterward (if (result < 0) { result += M; } [where M is the divisor, 2 in your example]).

Comments