浮动格式化为3或4位小数

时间:2014-12-02 01:12:50

标签: python floating-point rounding

我想将float格式化为严格 3或4位小数。

例如:

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  

'{:.5g}'.format(my_float)'{:.4f}'.format(my_float)的组合。

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

假设我理解你要问的内容,你可以将其格式化为4,然后删除尾随的' 0'如果有的话。像这样:

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'
相关问题