Dart language provides multiple static data types to store numeric values.
It provides the following primitive types to store the numeric values.
int
: stores whole numbers, Example numbers are 11,-14.double
: stores floating numbers that store fractional (decimal) digits of 64-bit double precision. Example numbers-24.43
,34.54.
Both int
and double
types extended from the num
object, which extends the object in Dart.
So, You can use num superclass in place of whole or floating numbers. numb will be used in arithmetic calculations that types of results not known at compile time.
The above all are reserved keywords that are not used as an identifier for variables functions or class names in Dart language.
How to Declare number variable?
Variables are declared like normal variables in Dart.
The default value for the int
and double
types is null
.
int variable_name=11;
double variable_name1=11.23;
In the above program.
- Variables are declared
- a type of the variable is declared, It tells the value type to be stored.
- numerical values are assigned to the variable on the same line.
variable_name
is a valid identifier in the dart
programming language.
If you assign an int
variable with a double value, It throws an Error: A value of type 'double' can't be assigned to a variable of type 'int'.
. Dart does not convert automatically.
The following are invalid int types
int number1=34.11;
If you assign a double
variable with an int
value, It does the automatic conversion.
Here is an example
void main() {
//declare int type variable
int number1=34;
print(number1); // 34
print(number1.runtimeType); // int
//declare double type variable
double floatingNumber=11.23;
print(floatingNumber); // 11.23
print(floatingNumber.runtimeType); // Double
}
Output:
34
int
11.23
double
Here is an example of a num type in dart.
void main() {
//declare int type variable
int number1 = 34;
//declare double type variable
double floatingNumber = 11.12;
// declare type num and assign with the addition of result
num result = number1 + floatingNumber;
print(result); // 11.23
print(result.runtimeType); // Double
}
Output:
45.12
double