OneBite.Dev - Coding blog in a bite size

Convert Variable From String To Float In Rust

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

Rust is a popular system programming language known for its safety, concurrency, and performance. In this article, we’ll take a deeper dive into one common task that developers carry out in Rust - converting a variable from string to float.

Code snippet: Converting a String to Float in Rust

The following code snippet shows you how to convert a string to float in Rust.

let my_string = "5.8";
let my_float: f32 = my_string.parse().unwrap();
println!("The value of my_float is: {}", my_float);

Code Explanation: Converting a String to Float in Rust

In Rust, the conversion of a string into a float is achieved by calling the parse method on the string. Here’s a step-by-step explanation of the code snippet above.

  1. Define the String to Convert: The first line let my_string = "5.8"; sets up a new string my_string with the value "5.8".

  2. Convert the String to a Float: The second line does the conversion. let my_float: f32 = my_string.parse().unwrap(); Here’s what it does:

    • my_string.parse() attempts to convert the string into another type. In this case, we’re converting it to a float.
    • The : f32 annotation explicitly specifies that the variable my_float is of type float. This is essential because the parse method needs to know what type we’re expecting.
    • unwrap() is then called to return the contained value if the parse operation completed successfully.
  3. Print the Float: The last line println!("The value of my_float is: {}", my_float); prints the converted float value.

Note that if the string cannot be parsed into a float (e.g., it contains letters), this code will panic due to the unwrap() call. If there’s a possibility of invalid input, you should handle the Result returned by parse() in a safer way, such as by using a match statement or the unwrap_or method.

rust