How to Check given number is an integer or whole number or decimal number in dart | Flutter By Example
In Dart, We have two numerical types - int, double
int
represents whole numbers, that contain no fractional or decimal digits double
stores the floating numbers that contain decimal values.
how to check given number is int or double?
There are multiple ways we can check
- using is Operator
dart is the operator used to check the variable of a given type or not
Syntax:
variable is datatype
Returns true if the variable of a given datatype else returns false. This check is added as an extension to num type.
Here is an example program to check given number is int or double.
void main() {
num intValue = 12;
num doubleValue = 11.12;
print(intValue.isIntValue()); // true
print(doubleValue.isIntValue()); // false
}
extension WholeNumber on num {
bool isIntValue() => this is int;
}
- using Modulus Operator
The modulus operator gives a remainder after two operand divisions.
if the given number is a whole number, Then the value is divided by 1 and gives the remainder as zero if the given number is a double or fractional decimal value, Then the remainder is not zero after division by 1
Here is an example program to check given number contains a fractional decimal or not.
void main() {
num intValue = 12;
num doubleValue = 11.12;
print(intValue.isIntValue()); // true
print(doubleValue.isIntValue()); // false
}
extension WholeNumber on num {
bool isIntValue() => (this % 1) == 0;
}
- use toInt method
The given number is truncated using the toInt
method. If the given number is 11.12, toInt returns int number i.e 11. Checks the original value and result, if both are equal, It is an integer number.
Here is an example program
void main() {
num intValue = 12;
num doubleValue = 11.12;
print(intValue.isIntValue()); // true
print(doubleValue.isIntValue()); // false
}
extension WholeNumber on num {
bool isIntValue() => this ==this.toInt();
}
Conclusion
There are multiple ways to check given a number is a whole number or a fractional decimal number in the dart examples below approaches.
- use toInt method
- dart is the operator
- using Modulus Operator