Rounding and displaying floats

Hi, could someone explain what is happening here, this is printing "1 0".
I don't know how format!() rounds but I was expecting it to round it to 1 as round() does.

fn main() {
    let n: f64 = 0.5;
    println!("{} {}", n.round(), format!("{:.0}", n));

It doesn't round. You 're just displaying your double with a precision of zero digits after the decimal point. The double is still 0.5, so without the fraction you get 0.

See answer by @quinedot below


Format precision does round (and not just truncate), but in a rounds to evens type fashion.

1 Like

Side note: That's the same as

println!("{} {:.0}", n.round(), n);
// or
println!("{} {n:.0}", n.round());

except your version allocates a String, writes the "{n:0}" to the String, passes the String to the println!, and then deallocates it.

I.e. there's no reason to use format!() since you're already in println!; they use the same formatting mechanisms.