In this chapter, we will learn about dart numbers data types and the properties and methods that are available in dart.
Dart Numbers
Numbers represent integer values and floating-point values. For example,
int number = 5;
For integer values, keyword int is used. Let’s see an example,
int number1 = 5;
int number2 = 88;
And for floating values, keyword double is used. For example,
double number1 = 5.324;
double number2 = 88.3258;
The num keyword represents numbers in general. Here’s an example,
num number1 =5.324;
num number2 = 5;
Number Properties
Dart also provides various properties and methods that make the life of a programmer easier.
Some of the Number properties are:
Property | Description |
isFinite | True if the number is finite |
isInfinite | True if the number is positive infinity or negative infinity |
isNaN | True if the number is the double Not-a-Number value |
hashcode | Returns a hash code for a numerical value |
isNegative | True if the number is negative |
isEven | Returns true if the number is even number |
isOdd | Returns true if the number is odd number |
sign | Returns -1, 0 or +1 depending on the sign and numerical value of the number |
Number Properties Example
void main() {
int number1 = 100;
print(number1.isFinite);
print(number1.isInfinite);
print(number1.isNaN);
print(number1.hashCode);
print(number1.isNegative);
int number2 = -100;
print(number2.isNegative);
print(number1.isEven);
print(number1.isOdd);
}
Output
true
false
false
100
false
true
true
false
Number Methods
Dart number data types also have various useful string methods available. Some of them are:
Methods | Description |
toInt() | Returns the integer equivalent of the number |
toDouble() | Returns the double equivalent of the number |
truncate() | Returns an integer after discarding any decimal digits |
round | Returns the integer closest to the current numbers |
floor | Returns the greatest integer not greater than the current number |
remainder | Returns the truncated remainder after dividing the two numbers |
toString | Returns the string equivalent representation of the number |
ceil | Returns the least integer no smaller than the number |
abs | Returns the absolute value of the number |
compareTo | Compare a number to another |
Number Methods Examples
void main() {
int number = 5;
double number1 = 5.224;
print(number1.toInt());
print(number1.truncate());
double number3 = 5.224;
double number4 = 5.66;
print(number3.round());
print(number4.round());
print(number3.floor());
print(number4.floor());
print(number.remainder(2));
print(number.toString());
print(number.compareTo(5));
print(number1.compareTo(5.224));
}
Output
5
5
5
6
5
5
1
5
0
0
That’s it for this chapter. See you one the next one.