2024-04-23 21:28:04 发布
网友
我想为以下规则选择表示浮点数的最佳方式:
input = 1500.000001 output = 1500 input = 1500.01 output = 1500.01 input = 1500 output = 1500
我尝试了两种方法,float_format=“.2g”和“.2f”,但它们都部分满足了我的规则。你知道吗
如果float_format=“.2g”,输出=1.5e3
如果float_format=“.2f”,输出=1500.00
假设我理解正确,我会用十进制。你知道吗
from decimal import Decimal input = 1500.00001 as_decimal = Decimal(input).quantize(Decimal('0.01')) >>> Decimal('1500.00')
另外,您可以检查它是int还是float。所以:
input = 1500 if type(input) == int: pass elif type(input) == float: input = Decimal(input).quantize(Decimal('0.01'))
假设我理解正确,我会用十进制。你知道吗
另外,您可以检查它是int还是float。所以:
相关问题 更多 >
编程相关推荐