以编程方式指定字符串格式的float的小数精度

时间:2014-09-01 17:19:37

标签: python formatting floating-point-precision

如何以编程方式指定字符串格式的float的小数精度?

具体来说,我想实现以下行为:

>>> print displayNumber(number=math.pi, precision=3)
3.142

1 个答案:

答案 0 :(得分:1)

使用旧的% - 格式样式,您可以执行以下操作:

>>> def displayNumber(number, precision):
>>>     return "%.*f" % (precision, number)

>>> def displayNumber(number, precision):
>>>     return ("%%.%df" % precision) % number
相关问题