Search code examples
dartdart2js

Dart2js numeric types: determining if a value is an int or a double


I'm trying to determine if a dynamic parameter to a function is really an int or a double and I'm finding surprising behavior (at least to me).

Can anyone explain this output (produced on dartpad)?

foo(value) {
  print("$value is int: ${value is int}");
  print("$value is double: ${value is double}");
  print("$value runtimetype: ${value.runtimeType}");
}

void main() {
  foo(1);
  foo(2.0);
  int x = 10;
  foo(x);
  double y = 3.1459;
  foo(y);
  double z = 2.0;
  foo(z);
}

The output:

1 is int: true
1 is double: true
1 runtimetype: int
2 is int: true
2 is double: true
2 runtimetype: int
10 is int: true
10 is double: true
10 runtimetype: int
3.1459 is int: false
3.1459 is double: true
3.1459 runtimetype: double
2 is int: true
2 is double: true
2 runtimetype: int

Solution

  • In the browser there is no distinction possible between int and double. JavaScript doesn't provide any such distinction and introducing a custom type for this purpose would have a strong impact on performance, which is why this wasn't done.

    Therefore for web applications it's usually better to stick with num.

    You can check if a value is integer by using for example:

    var val = 1.0;
    print(val is int);
    

    prints true

    This only indicates that the fraction part is or is not 0.

    In the browser there is no type information attached to the value, so is int and is double seem to just check to see if there is a fractional component to the number and decide based on that alone.