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

心不动则不痛 提交于 2020-04-14 01:10:49

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/43949093/dart2js-numeric-types-determining-if-a-value-is-an-int-or-a-double

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!