Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format float with given precision ignoring trailing zeros

Tags:

rust

I'm looking for a way to format! a var: f64 with a given precision prec.

I know I can format!("{:1$}", var, prec). Problem is, given var=3.1 and prec=3, I'll get "3.100" as output. I'm looking for a way to omit those trailing zeros, so when var=3.1 output is "3.1", 3.0 => "3" and 3.14159 => "3.142".

Is there a not so hard way to achieve this?

like image 619
Marcelo Vogt Avatar asked Jun 02 '26 19:06

Marcelo Vogt


1 Answers

Assuming you mean "trailing zeroes", you can use my library float_pretty_print. It attains output similar to what you want by running standard float formatter multiple times and choosing the appropriate output. You can set minimum and maximum width.

$ cargo run --example=repl
Type number to be formatted using float_pretty_print
Also type `width=<number>` or `prec=<number>` to set width or precision.
3.1
3.1
3.12345
3.12345
prec=5
3.1
3.1
3.12345
3.123
width=5
3.1
3.100

Note that instead of precision, you set maximum width in characters of the whole output (not just the fractional).

Also do not expect high performance - the library may allocate multiple times for processing one number.

like image 174
Vi. Avatar answered Jun 05 '26 13:06

Vi.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!