How to Convert Float to Integer in Rust
Created
Modified
Using as Keyword
Executing an as expression casts the value on the left-hand side to the type on the right-hand side.
An example of an as expression:
fn main() {
let a = 3.6415_f64;
let b = a as i64;
println!("{}", b);
}
3
Using round Function
The round()
function returns the nearest integer to a number. Round half-way cases away from 0.0.
See the following example:
fn main() {
let a = 3.6415_f64;
let mut b = a.round() as i64;
println!("round: {}", b);
b = a.trunc() as i64;
println!("trunc: {}", b);
b = a.ceil() as i64;
println!("ceil: {}", b);
b = a.floor() as i64;
println!("floor: {}", b);
}
round: 4 trunc: 3 ceil: 4 floor: 3