OneBite.Dev - Coding blog in a bite size

Convert Variable From Float To String In Rust

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

Rust programming language is renowned for its memory safety without needing a garbage collector. This article will walk you through a simple task in Rust, converting a variable from Float to String.

Code snippet for Converting Float to String

Let’s look at the code snippet below:

fn main() {
    let num: f32 = 10.5;
    let string_num = num.to_string();
    println!("The number as a string is: {}", string_num);
}

In this code snippet, we create a float num and then convert it to a string string_num.

Code Explanation for Conversion from Float to String

In the start, we declare a function named main. It is the primary function in all executable Rust programs.

fn main() {

After the function declaration, we declare and initialize a float named num with a value of 10.5.

let num: f32 = 10.5;

To convert the float num to a string, we use Rust’s built-in to_string() function. We store the resulting string in a new variable, string_num.

let string_num = num.to_string();

Finally, we print string_num to the console to check our result. The placeholder {} inside the string will hold the value of string_num.

println!("The number as a string is: {}", string_num);

We close the main() function with a closing bracket:

}

The to_string() function tries to convert the float to a string, and as a result, we get the string version of our float. Thus the variable has been successfully converted from a float to a string in Rust. Going through these will not only help you understand the basic functioning of Rust but also provide you with the knowledge to manipulate and convert various data types.

rust