Nathan Crabbe
Nathan Crabbe

Reputation: 155

Float formatting to 3 or 4 decimal places

I would like to format a float to 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 a combination of '{:.5g}'.format(my_float) and '{:.4f}'.format(my_float).

Any ideas?

Upvotes: 1

Views: 1894

Answers (1)

dkamins
dkamins

Reputation: 21918

Assuming I understand what you're asking, you can format it to 4 then drop the trailing '0' if there is one. Like this:

def fmt_3or4(v):
    """Format float to 4 decimal places, or 3 if ends with 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'

Upvotes: 4

Related Questions