【问题标题】:Avoid rounding in new python string formatting避免在新的 python 字符串格式中舍入
【发布时间】:2014-03-13 06:37:07
【问题描述】:

我想在我的脚本中用新的 python 字符串格式化语法替换旧的字符串格式化行为,但是在处理浮点数时如何避免舍入?

旧版本

print ('%02d:%02d:%02d' % (0.0,0.9,67.5))

收益00:00:67

而我的(显然是错误的)翻译成新的语法

print ('{0:0>2.0f}:{1:0>2.0f}:{2:0>2.0f}'.format(0.0,0.9,67.5))

产生00:01:68

如何避免此处舍入并使用新格式语法获取旧输出?

【问题讨论】:

标签: python string format


【解决方案1】:

“规则”很简单:

'%d' % 7.7         # truncates to 7
'%.0f' % 7.7       # rounds to 8
format(7.7, 'd')   # refuses to convert
format(7.7, '.0f') # rounds to 7

要完全控制演示文稿,您可以将浮点数预先转换为整数。根据您的需要,有几种方法可以做到这一点:

>>> math.trunc(f) # ignore the fractional part
67
>>> math.floor(f) # round down
67
>>> math.ceil(f)  # round up
68
>>> round(f)      # round nearest
68

【讨论】:

    【解决方案2】:

    将参数显式转换为ints:

    >>> '{:02}:{:02}:{:02}'.format(int(0.0), int(0.9), int(67.5))
    '00:00:67'
    

    顺便说一句,如果您使用 Python 2.7+、Python 3.1+(自动编号),则无需指定参数索引({0}{1}、..)。

    【讨论】:

    • 糟糕,您正在明确转换为int :( 我认为format 有办法截断小数部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    相关资源
    最近更新 更多