the operation % in Dart return a strange value% work in Dart

Viewed 3564

The var c return 3 but 10/7=1.4285, the rest is 0.4285, operator % has a bug?

void main() {
  var a = 10;
  var b = 7;
  var c;
  c = a % b;
  print(c);
}
2 Answers

From the documentation of the % operator on num in Dart:

Euclidean modulo operator.

Returns the remainder of the Euclidean division. The Euclidean division of two integers a and b yields two integers q and r such that a == b * q + r and 0 <= r < b.abs().

The Euclidean division is only defined for integers, but can be easily extended to work with doubles. In that case r may have a non-integer value, but it still verifies 0 <= r < |b|.

The sign of the returned value r is always positive.

See remainder for the remainder of the truncating division.

https://api.dart.dev/stable/2.8.4/dart-core/num/operator_modulo.html

The '%' operator returns the remainder left after dividing two numbers. It does not return the decimal part. For example:

10 / 7

    1
  ______
7 ) 10
   - 7
  ______
     3

So it returns 3 which is what remains after dividing 10 by 7 without any decimals. 10 / 7 = 1 3/7

What you want to do can be accomplished like this:

var floatNumber = 12.5523;
var x = floatNumber - floatNumber.truncate();
Related