To convert a string to a float in Rust, you can use the 'parse()' method and 'unwrap()' to handle the Result.
In this example,
str1
with a value of "3.14"
.parse()
method to convert the string to a float and use unwrap()
to handle the Result, storing the float value in float1
.float1
.// Convert "3.14" String to Float
fn main() {
let str1 = "3.14";
let float1: f32 = str1.parse().unwrap();
println!("Float value is: {}", float1);
}
Float value is: 3.14
In this example,
str2
with a value of "10.5"
.parse()
method to convert the string to a float and use unwrap()
to handle the Result, storing the float value in float2
.float2
.// Convert "10.5" String to Float
fn main() {
let str2 = "10.5";
let float2: f32 = str2.parse().unwrap();
println!("Float value is: {}", float2);
}
Float value is: 10.5
In this tutorial, we learned How to convert String to Float in Rust language with well detailed examples.