Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter check if variable is NaN

Tags:

flutter

dart

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?

like image 424
Tree Avatar asked Jul 06 '18 01:07

Tree


People also ask

How do you deal with 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).

How do you check if a value is int in flutter?

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 .

How do you check numeric values in flutter?

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.


1 Answers

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.

like image 86
felix-ht Avatar answered Sep 20 '22 08:09

felix-ht