Search code examples
rust

How to format a float without trailing zeros in Rust?


I'm formatting f64 like this:

format!("{:.8}", x)

This returns strings like this:

110.00000000
601.47000000
4.50000000

I'm looking to remove all the extra zeros at the end of each so that the output is this:

110
601.47
4.5

I'm hoping to do this without any external crates or libraries (not a big deal if it has to happen though). Is there something built-in to Rust that can accomplish this? Or will I have to write a custom function to do so?

Edit:

I should add that I can't simple do format("{}", x) because that will return strings like this:

40.019999999999996
1192.6499999999999
2733.9599999999996

Is there a way around that?


Solution

  • This currently solves the issue for me:

    let y = (x * 100_000_000.0).round() / 100_000_000.0;
    format!("{}", y);
    

    I will keep an eye out for any better solutions. Thank you!