Python: format float to a minimum floating point precision if needed

Say I have two numbers 1.2 and 1.24898, how do I format the string such that anything without sufficient precision always is fixed to two floating points (.2f) but anything with more than 2 will retain their floating points?

I want this to be printed as: 1.20 and 1.24898. Is there a way of doing this via print formatting or a pythonic way?

Doing print(f'{1.24898:,.2f}') will cause it to be fixed to 2 places, but I want to retain all its precision. And similarly the same for the 1.2 i want it printed as 1.20.



Read more here: https://stackoverflow.com/questions/65721025/python-format-float-to-a-minimum-floating-point-precision-if-needed

Content Attribution

This content was originally published by user1757703 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: