我希望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?。
当前回答
我看到的答案对浮点数(52.15)不起作用。经过一些测试,我使用的解决方案是:
import decimal
def value_to_decimal(value, decimal_places):
decimal.getcontext().rounding = decimal.ROUND_HALF_UP # define rounding method
return decimal.Decimal(str(float(value))).quantize(decimal.Decimal('1e-{}'.format(decimal_places)))
(将“value”转换为float和string非常重要,这样一来,“value”可以是float、decimal、integer或string类型!)
希望这对任何人都有帮助。
其他回答
只需使用此函数并将字节作为输入传递给它:
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的最简单方法。
有新的格式规范,字符串格式规范迷你语言:
您可以执行以下操作:
"{:.2f}".format(13.949999999999999)
注1:上面返回一个字符串。为了获得float,只需用float(…)包装:
float("{:.2f}".format(13.949999999999999))
注意2:用float()换行不会改变任何内容:
>>> x = 13.949999999999999999
>>> x
13.95
>>> g = float("{:.2f}".format(x))
>>> g
13.95
>>> x == g
True
>>> h = round(x, 2)
>>> h
13.95
>>> x == h
True
打印百分比的单行函数:
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”
我们有多种选择:
选项1:
x = 1.090675765757
g = float("{:.2f}".format(x))
print(g)
选项2:内置round()支持Python 2.7或更高版本。
x = 1.090675765757
g = round(x, 2)
print(g)
orig_float = 232569 / 16000.0
14.5355625
short_float = float("{:.2f}".format(orig_float))
14.54