如何使用Python在“.xg”和“.xf”之间选择float\u格式?

2024-04-23 21:28:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为以下规则选择表示浮点数的最佳方式:

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


Tags: 方法formatinputoutput规则方式float浮点数
1条回答
网友
1楼 · 发布于 2024-04-23 21:28:04

假设我理解正确,我会用十进制。你知道吗

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'))

相关问题 更多 >