rust round 2 decimal places
To round a number in Rust to 2 decimal places, you can use the round
function from the num_traits
crate. Here's an example:
use num_traits::Float;
fn round_to_2_decimal_places(num: f64) -> f64 {
num.round_at(2)
}
fn main() {
let num = 3.14159265359;
let rounded_num = round_to_2_decimal_places(num);
println!("Rounded number: {}", rounded_num);
}
In this example, we import the Float
trait from the num_traits
crate. The Float
trait provides the round_at
method, which allows us to round a floating-point number to a specified number of decimal places. We define a function round_to_2_decimal_places
that takes a f64
number as input and returns the rounded number. Inside the main
function, we call round_to_2_decimal_places
with a sample number and print the rounded result.