OneBite.Dev - Coding blog in a bite size

Convert Variable From Int To Float In Dart

Code snippet for how to Convert Variable From Int To Float In Dart with sample and detail explanation

In programming, variable type conversion is a common requirement. This article will focus on how to convert a variable from int to float in Dart, along with a detailed explanation of the relevant steps.

Code snippet for Variable Conversion

Here’s the necessary code to fulfil this task:

void main() { 
   int number = 6; 
   double doubleNumber = number.toDouble();
   print(doubleNumber);
}

After running this code, the output will be: 6.0

Code Explanation for Variable Conversion

This code’s primary purpose is using the toDouble() method to convert an int to a double. Since Dart does not support the data type float, the double data type is used for the floating-point numbers. When you need to convert an int to a float in Dart, this method comes in handy.

In the first line, an int variable called number is defined with the value 6.

   int number = 6; 

In the next line, the method toDouble() is applied to the number variable and the resulting value is stored in a new variable doubleNumber. The toDouble() method converts an int to a double.

   double doubleNumber = number.toDouble();

The third line allows us to output the result, which is 6.0. It shows that the int variable has been successfully converted into a double or float variable.

   print(doubleNumber);

Important to remember that using the toDouble() method does not modify the original int value but returns a new double value. Therefore, the original int variable, in this case number, remains unaltered.

dart