Dart2js numeric types: determining if a value is int or double
I'm trying to determine if a parameter dynamic
for a function is valid int
or double
, and I find surprising behavior (at least for me).
Can anyone explain this output (generated 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);
}
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
source to share
There is no difference in the browser between int
and double
. JavaScript does not make this distinction, and introducing a special type for this purpose would have a dramatic performance impact, so this was not done.
So for web apps it's usually best to stick with num
.
You can check if a value is an integer using for example:
var val = 1.0;
print(val is int);
prints true
It only indicates what part of the fraction is or is not 0
.
The browser doesn't have any type information bound to the value, so is int
it is double
looks like they just check if there is a fractional component for the number and decide based on that.
source to share