Convert Variable From Float To Int In Rust
Code snippet for how to Convert Variable From Float To Int In Rust with sample and detail explanation
Rust, a modern, highly efficient system programming language focuses on safety, speed and concurrency. One of the common tasks while programming in Rust is manipulating data types like converting a variable from float to int.
Code snippet for Converting Variable From Float To Int In Rust
Here’s a simple code snippet demonstrating how to do this:
fn main() {
let float_value: f32 = 10.5;
let converted_int: i32 = float_value as i32;
println!("Converted Value: {}", converted_int);
}
Code Explanation for Converting Variable From Float To Int In Rust
-
Start by calling the function
main()
. This is the starting point of the Rust program; -
Inside the
main()
function, define the float variablefloat_value
usinglet
. In Rust,let
is used for variable binding. Here we bind the float number10.5
to the variablefloat_value
; -
Next, define another variable,
converted_int
, again using thelet
keyword. Theas
keyword is used to convert thefloat_value
into an integer. Withas
, you can perform a safe type casting, which converts one primitive type to another. Thef32
value is cast toi32
. The fractional part of the float will be ignored during this conversion; -
The
println!
macro is used to print the converted value to the console.
Running the code snippet will output: “Converted Value: 10”, because as we pointed out, the .5 fractional part was ignored during the conversion from float to int.
Remember, Rust is a statically typed language that cares about the type of value you are assigning to the variable. Make sure to declare all your variables with their types if they are not immediately obvious as in the example provided here. Using the right data types ensures we obtain the results and behaviors expected from our Rust programs.