python - Float formatting to 3 or 4 decimal places -


i format float strictly 3 or 4 decimal places.

for example:

1.0     => 1.000   # 3dp   1.02    => 1.020   # 3dp   1.023   => 1.023   # 3dp   1.0234  => 1.0234  # 4dp   1.02345 => 1.0234  # 4dp   

kind of combination of '{:.5g}'.format(my_float) , '{:.4f}'.format(my_float).

any ideas?

assuming understand you're asking, can format 4 drop trailing '0' if there one. this:

def fmt_3or4(v):     """format float 4 decimal places, or 3 if ends 0."""     s = '{:.4f}'.format(v)     if s[-1] == '0':         s = s[:-1]     return s  >>> fmt_3or4(1.02345) '1.0234' >>> fmt_3or4(1.023) '1.023' >>> fmt_3or4(1.02) '1.020' 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -