-1

我尝试在下面创建一个温度转换器:

from decimal import *
getcontext().prec = 10

celsius = Decimal(12)
fahrenheit = celsius*9/5+32
kelvin = celsius+Decimal(273.15)
romer = celsius*21/40+Decimal(7.5)

转换为字符串时,fahrenheit返回53.6romer返回13.8,都没有额外的小数位。但是,kelvin返回285.1500000. (这甚至不是285.1500001)。我如何确保它返回足够的地方,即285.15?我认为添加浮动小数不是问题,因为romer很好。

4

3 回答 3

0

为简单起见,您可以使用内置round()函数。它有两个参数,需要四舍五入的数字和要四舍五入的小数位数。

kelvin = round(celsius+Decimal(273.15), 2)

这里285.1500000将四舍五入到小数点后2位285.15。也可以使用其他方法,例如str.format(), trunc(),round_up()等。

于 2022-02-25T07:30:57.107 回答
0

做简单

from decimal import *
getcontext().prec = 10

celsius = Decimal(12)
fahrenheit = celsius*9/5+32
kelvin = round(celsius+Decimal(273.15), 2) #if you need more then 2 digit replace 2 with other number
romer = celsius*21/40+Decimal(7.5)
于 2022-02-25T07:17:14.647 回答
-1

您也许可以使用str.format(). 例如:

formatted_kelvin = "{:.2f}". format(kelvin)

所以,如果你打印这个,它只会打印 2 个小数位。

于 2022-02-25T00:29:08.237 回答