我希望a四舍五入到13.95。我试过用圆形,但我得到:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。
我希望a四舍五入到13.95。我试过用圆形,但我得到:
>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999
有关标准库Decimal类的类似问题,请参阅How can I format a Decimal to always show 2 Decimal places?。
当前回答
对于原始Python:
对于浮点到字符串转换的2个小数点:
a = 13.949999999999999
format(a, '.2f')
对于浮点到浮点转换的2个小数点:
a = 13.949999999999999
round(float(a), 2)
or
float(format(a, '.2f'))
其他回答
您可以修改输出格式:
>>> a = 13.95
>>> a
13.949999999999999
>>> print "%.2f" % a
13.95
对于Python<3(例如2.6或2.7),有两种方法可以实现。
# Option one
older_method_string = "%.9f" % numvar
# Option two (note ':' before the '.9f')
newer_method_string = "{:.9f}".format(numvar)
但请注意,对于3以上的Python版本(例如3.2或3.3),首选选项二。
有关选项2的更多信息,我建议使用Python文档中的字符串格式链接。
关于选项一的更多信息,这个链接就足够了,并提供了各种标志的信息。
引用:将浮点数转换为特定精度,然后复制为字符串
打印百分比的单行函数:
k——分子
n-分母
“%.2f”-表示需要2位小数的精度
*100-将数字从小数转换为百分比
percentage = lambda k, n: '%.2f' % (k/n*100)
- equivalent to-
def percentage(k,n):
return '%.2f' % (k/n*100)
百分比(1,3)
输出->“33.33”
from decimal import Decimal
def round_float(v, ndigits=2, rt_str=False):
d = Decimal(v)
v_str = ("{0:.%sf}" % ndigits).format(round(d, ndigits))
if rt_str:
return v_str
return Decimal(v_str)
结果:
Python 3.6.1 (default, Dec 11 2018, 17:41:10)
>>> round_float(3.1415926)
Decimal('3.14')
>>> round_float(3.1445926)
Decimal('3.14')
>>> round_float(3.1455926)
Decimal('3.15')
>>> round_float(3.1455926, rt_str=True)
'3.15'
>>> str(round_float(3.1455926))
'3.15'
大多数数字不能用浮点数精确表示。如果你想舍入这个数字,因为这是你的数学公式或算法所要求的,那么你想使用舍入。如果您只想将显示限制为某一精度,那么甚至不要使用舍入,只需将其格式化为字符串即可。(如果您想用其他舍入方法显示,并且有吨,则需要混合使用这两种方法。)
>>> "%.2f" % 3.14159
'3.14'
>>> "%.2f" % 13.9499999
'13.95'
最后,也许最重要的是,如果你想要精确的数学,那么你根本不需要浮点数。通常的例子是处理货币,并将“美分”存储为整数。