I have var number;
and it gets assigned by some calculations.
If I do print(number);
I get NaN
as response;
I expected that I would be able to do something like
if (number is NaN)
But I get NaN is not defined.
How to check if variable is NaN
in flutter?
In fact if you would want to implement a NaN check yourself you would do it like so: bool isNan(double x) => x != x; This also has the consequence that if you save a NaN into any other kind of object, the object will no longer be equal to itself (as long as the NaN is used in the comparison - like with data classes).
Dart numbers (the type num ) are either integers (type int ) or doubles (type double ). It is easy to check if a number is an int , just do value is int .
To check whether a string is a numeric string, you can use the double. tryParse() method. If the return equals null then the input is not a numeric string, otherwise, it is.
You cannot check for nan by comparing it to the double.nan constant. isNan is the way to go.
yourNumber.isNaN
Why does comparing to double.nan not work?
print(double.nan == double.nan);
// prints false
print(double.nan.isNaN);
// prints true
This is because by definition NaN is not equal to itself. In fact if you would want to implement a NaN check yourself you would do it like so:
bool isNan(double x) => x != x;
This also has the consequence that if you save a NaN into any other kind of object, the object will no longer be equal to itself (as long as the NaN is used in the comparison - like with data classes). This can lead to unexpected behavior. You could use this code to check for this case.
bool hasNan(Object? x) => x != x;
In general this is true for all languages i am aware of - not just dart - as it's a hardware thing.
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