'Format float with given precision ignoring trailing zeros

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source