Open In App

Basics of Numbers in Dart

Like other languages, Dart Programming also supports numerical values as Number objects. The number in Dart Programming is the data type that is used to hold the numeric value. Dart numbers can be classified as: 



int: The int data type is used to represent whole numbers.

Syntax: int var_name;



double: The double data type is used to represent 64-bit floating-point numbers.

Syntax: double var_name;

Example 1: 
 




void main() {
   
   // declare an integer
   int num1 = 2;            
      
   // declare a double value
   double num2 = 1.5; 
 
   // print the values
   print(num1);
   print(num2);
}

Output: 

2
1.5

Note: The num type is an inherited data type of the int and double types.

Parsing in Dart: The parse() function is used parsing a string containing numeric literal and convert to the number. 
 

Example 2: 
 




void main()
{
   
  var a1 = num.parse("1"); 
  var b1 = num.parse("2.34"); 
 
  var c1 = a1+b1;  
  print("Product = ${c1}"); 

Output: 

Product = 3.34

Properties: 

Methods: 

Some try-error for num:

1)




void main(){
 
    int x = 10;
    x = 20.5; // Error: A value of type 'double' can't be assigned to
      // a variable of type 'int'.
 
    num y = 10;
    y = 10.5; // No Error
}

That means we can use num data type if we don't know the actual type of input, if it might be an int or double.

2)




void main(){
 
    double y = 10; // We can store the int value into the double data type but
      // we can't store double value in int type.
    y = 10.5;
}

We can store the int value into the double data type but we can't store double value in int type.


Article Tags :