Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart/Flutter check if value is an integer/whole number

How do I check if a value is a whole number (integer) or contains a decimal? In Javascript we have isInteger but I couldn't find the equivalent in Dart.

We seem to have checks for isEven, isOdd, isFinite, isInfinite, isNaN and isNegative but no isInteger?

like image 547
Hasen Avatar asked Sep 19 '19 12:09

Hasen


People also ask

How do you check if a value is an integer in flutter?

It is easy to check if a number is an int , just do value is int . The slightly harder task is to check whether a double value has an integer value, or no fractional part. There is no simple function answering that, but you can do value == value. roundToDouble() .

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.

How do you check if a float is a whole number?

To check if a float value is a whole number with Python, we can use the is_integer method. to check if 1.0 is an integer by calling is_integer on it. It'll return True if it is and False otherwise.


Video Answer


3 Answers

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.

The slightly harder task is to check whether a double value has an integer value, or no fractional part. There is no simple function answering that, but you can do value == value.roundToDouble(). This removes any fractional part from the double value and compares it to the original value. If they are the same, then there was no fractional part.

So, a helper function could be:

bool isInteger(num value) => 
    value is int || value == value.roundToDouble();

I use roundToDouble() instead of just round() because the latter would also convert the value to an integer, which may give a different value for large double values.

like image 118
lrn Avatar answered Oct 16 '22 20:10

lrn


Use the modulo operator %:

  bool isInteger(num value) => (value % 1) == 0;

Same as an extension method:

  extension NumExtensions on num {
    bool get isInt => (this % 1) == 0;
  }

Usage:

  double d = 2.6;
  double d2 = 2.0;
  int i = 2;
  print(d.isInt); // returns false
  print(d2.isInt); // returns true
  print(i.isInt); // returns true
like image 15
kine Avatar answered Oct 16 '22 18:10

kine


void main() {
  int a = 10;
  print(a is int); // Prints true
}

OR

void main() {
  dynamic a = 10;
  print(a is int ? a/10 :"Not an int"); // Prints 1
}
like image 6
Sharad Paghadal Avatar answered Oct 16 '22 19:10

Sharad Paghadal