OneBite.Dev - Coding blog in a bite size

Convert Variable From String To Float In Dart

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

In the world of programming, being able to manipulate and convert variable types is a skill that could help in making more efficient and error-free programs. In this article, we’ll discuss how to take a string variable and convert it into a float in the Dart programming language.

Code snippet: Convert String to Float in Dart

To convert a string to a float (double in Dart), we will use the parse method from the double class. Here is a simple code snippet that demonstrates how to do this.

void main() { 
  String strNumber = "10.50"; 
  double floatNumber; 

  floatNumber = double.parse(strNumber); 

  print(floatNumber);
}

When you run this program, it will output 10.5 which is the float equivalent of the string "10.50".

Code Explanation: Convert String to Float in Dart

In this section, we’ll explain each step in detail to help you fully understand how conversion from string to float is done.

  1. Step 1: We first declare and initialize our strNumber with a string-number "10.50".
    String strNumber = "10.50"; 
  1. Step 2: We then declare another variable floatNumber of type double. In Dart, double is used to represent floating point literals. variables of type double can store fractional numbers.
    double floatNumber; 
  1. Step 3: The next step is the actual conversion. We use the Dart’s built-in double.parse() method for this. The double.parse() function attempts to convert the string to a double. If the string cannot be converted to a number (like if the string was “Hello” instead of “10.50”), then the program would crash with an error.
    floatNumber = double.parse(strNumber); 
  1. Step 4: Finally we print the floatNumber to our console. floatNumber is now a double that you can do calculations or any other operations you would with a floating point number.
    print(floatNumber);

With these steps, you should be able to convert any string that contains a numeric value into a float in Dart. It’s a simple yet useful conversion method in Dart programming.

dart