I tried this code on Dart: I get 28.5
void main() {
double modulo = -1.5 % 30.0;
print(modulo);
}
The same code in Javascript returns -1.5
let modulo = -1.5 % 30;
console.log(modulo);
What is the equivalent of the javascript code above in Dart ?
An issue was raised about this in the dart-lang repo a while ago. Apparently the % symbol in dart is an "Euclidean modulo operator rather than remainder."
An equivalent of what you are trying to do can be accomplished with
(-1.5).remainder(30.0)
The documentation for num.operator % states (emphasis mine):
Returns the remainder of the Euclidean division. The Euclidean division of two integers
aandbyields two integersqandrsuch thata == b * q + rand0 <= r < b.abs()....
The sign of the returned value
ris always positive.See
remainderfor the remainder of the truncating division.
Meanwhile, num.remainder says (again, emphasis mine):
The result
rof this operation satisfies:this == (this ~/ other) * other + r. As a consequence the remainderrhas the same sign as the dividerthis.
So if you use:
void main() {
double modulo = (-1.5).remainder(30.0);
print(modulo);
}
you'll get -1.5.
Note that both values are mathematically correct; there are two different answers that correspond to the two different ways that you can compute a negative quotient when performing integer division. You have a choice between rounding a negative quotient toward zero (also known as truncation) or toward negative infinity (flooring). remainder corresponds to a truncating division, and % corresponds to a flooring division.
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