Force "." in f32 printing

#[test]
fn test_00() {
    println!("{}", 0.0_f32);}

prints out "0". I would prefer output "0." or anything else with a "." in it (so I can read back as Rust code).

Is there a way to force "." to be printed for f32 ?

You can force the precision to be 1, but that will cause truncation.

Playground

fn main() {
    println!("{:.1}", 0.0);

    println!("{:.1}", 0.0001);
}

Output:

0.0
0.0

I don't think there's a way to make that work with the fmt module, though you could always check if a decimal point was added and add one if it wasn't.

1 Like
println!("{}_f32", 0.0_f32);

― ? ―

5 Likes

Using Debug formatting instead of Display will print the dot.

fn main() {
    println!("{:?}", 0.0);
}
1 Like

If that's the goal, then the crate for that is

2 Likes

Not guaranteed though.

For round-trips, maybe "{:e}" is better? It will be shorter for very large or small exponents, at least.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.