我希望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?。
当前回答
lambda x, n:int(x*10^n + 0.5)/10^n
他为我工作了很多年,精通多种语言。
其他回答
Use:
float_number = 12.234325335563
round(float_number, 2)
这将返回;
12.23
说明:
round函数接受两个参数;要舍入的数字和要返回的小数位数。这里我返回了两位小数。
只需使用此函数并将字节作为输入传递给它:
def getSize(bytes):
kb = round(bytes/1024, 4)
mb = round(kb/1024, 4)
gb = round(mb/1024, 4)
if(gb > 1):
return str(gb) + " GB"
elif(mb > 1):
return str(mb) + " MB"
else:
return str(kb) + " KB"
这是将数据大小从字节动态转换为KB、MB或GB的最简单方法。
下面是使用format函数的简单解决方案。
float(format(num, '.2f'))
注意:我们将数字转换为浮点数,因为format方法返回字符串。
要将一个数字舍入为一个分辨率,最好的方法是以下方法,该方法可以适用于任何分辨率(两个小数或甚至其他步长为0.01):
>>> import numpy as np
>>> value = 13.949999999999999
>>> resolution = 0.01
>>> newValue = int(np.round(value/resolution))*resolution
>>> print newValue
13.95
>>> resolution = 0.5
>>> newValue = int(np.round(value/resolution))*resolution
>>> print newValue
14.0
使用Decimal对象和round()方法的组合。
Python 3.7.3
>>> from decimal import Decimal
>>> d1 = Decimal (13.949999999999999) # define a Decimal
>>> d1
Decimal('13.949999999999999289457264239899814128875732421875')
>>> d2 = round(d1, 2) # round to 2 decimals
>>> d2
Decimal('13.95')