flutterdartinteger

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?


Solution

  • 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.

    Another test for a double having an integer value could be value % 1.0 == 0.0, but it's not more readable, unlikely to be more efficient, and even though it does actually work, I had to check what % 1.0 does for double.infinity (it gives NaN) before I could trust it.