Convert Variable From Int To Float In Rust
Code snippet for how to Convert Variable From Int To Float In Rust with sample and detail explanation
Rust is a powerful, system-level language primarily used for performance-critical applications and system development. In this article, we’ll discuss a fundamental topic in Rust: changing a variable from an integer data type to a floating-point.
Code snippet: Converting integer to float in Rust
let integer_var = 5;
let float_var = integer_var as f64;
println!("The floating version of {} is {}.", integer_var, float_var);
Code Explanation: Converting integer to float in Rust
In Rust, we start declaring variables with the let
keyword.
In the first line of the snippet:
let integer_var = 5;
We declare a variable named integer_var
and assign the integer value 5
to it.
The second line:
let float_var = integer_var as f64;
Here, we declare another variable, float_var
. We then take our integer variable integer_var
and convert it to a floating-point number using the as
keyword followed by the type we want to convert to, in this case, f64
, which denotes a 64-bit floating-point number.
The keyword as
in Rust is used for type-casting or type conversion operations.
In the third line:
println!("The floating version of {} is {}.", integer_var, float_var);
We print a statement on the console replacing {}
with our integer and float variables accordingly.
The console will output: “The floating version of 5 is 5.0.”
Understand this guide, and you’ll have no problems handling the conversion of an integer to a floating-point in Rust. But bear in mind that Rust has both f64
and f32
for double precision and single precision floating point numbers respectively, so convert according to what precision you need.