OneBite.Dev - Coding blog in a bite size

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

  1. Start by calling the function main(). This is the starting point of the Rust program;

  2. Inside the main() function, define the float variable float_value using let. In Rust, let is used for variable binding. Here we bind the float number 10.5 to the variable float_value;

  3. Next, define another variable, converted_int, again using the let keyword. The as keyword is used to convert the float_value into an integer. With as, you can perform a safe type casting, which converts one primitive type to another. The f32 value is cast to i32. The fractional part of the float will be ignored during this conversion;

  4. 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.

rust