5

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?

Harrison
  • 116
  • 1
  • 8

2 Answers2

2

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!

Harrison
  • 116
  • 1
  • 8
-1

You can just do

format!("{}", x)

The {:.8} requires 8 places of precision, and thus, prints out extra zeros to that precision.

kopecs
  • 1,545
  • 10
  • 20
  • 2
    Not quite what I'm looking for, as that returns strings like this:56.74000000000001 8.940000000000001 89.63000000000001 103.42999999999998 – Harrison Dec 27 '19 at 23:00
  • That just looks like a natural fact of floating point imprecision, you'd just have to choose when you're close enough for your purposes to round. – kopecs Dec 27 '19 at 23:44
  • 2
    Your caveat doesn't answer the OP's question it just rationalizes why it's the way it is – flow Oct 30 '21 at 09:03