Reputation: 69
How do I check if a value is a number (even or odd) with type double in Dart?
Upvotes: 5
Views: 18280
Reputation: 261
Here is the code to detect from String.
bool isDouble(String? s) {
if (s == null) {
return false;
}
if(int.tryParse(s)!=null){
return false;
}
return double.tryParse(s)!= null;
}
Upvotes: 0
Reputation: 69
There are native methods for int
to achieve that purposes. You can convert the number to an int
and call number.isOdd
, number.isEven
...
Documentation:
abstract class int extends num {
/// Returns true if and only if this integer is odd.
bool get isOdd;
// Returns true if and only if this integer is even.
bool get isEven;
}
Upvotes: 4
Reputation: 733
You can go traditional with String evenOrOdd = number %2 == 0?'even':'odd'
Upvotes: 3
Reputation: 6257
double value = 2.5;
print(value.floor().isEven ? "It's even" : "It's odd");
Upvotes: 8