Reputation: 31391
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?
Upvotes: 24
Views: 22809
Reputation: 13
Use isFinite property https://api.flutter.dev/flutter/dart-core/num/isFinite.html
value.isFinite
Upvotes: 0
Reputation: 2075
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.
Upvotes: 15
Reputation: 9274
num
types have an isNaN
property, or you can see if the var is equal to double.nan
. You should define the variable using num
instead of var
.
https://api.dartlang.org/stable/1.24.3/dart-core/num-class.html
Upvotes: 0
Reputation: 31386
NAN is a CONSTANT so you can do this
if (number == double.nan)
also you have this property isNaN but to use it you must provide the type because it's available only for num
s so either double
or int
if (number.isNaN)
Upvotes: 30