不幸的是,似乎甚至没有带有
float.__format__这种格式的新格式。
floats的默认格式与
repr;相同;并带有
f标志,默认情况下有6个小数位:
>>> format(0.0000000005, 'f')'0.000000'
但是,有一种技巧可以达到预期的效果-不是最快的,而是相对简单的:
- 首先,使用
str()
或将浮点数转换为字符串repr()
- 然后
Decimal
从该字符串创建一个新实例。 Decimal.__format__
支持f
提供期望结果的标志,并且与float
s不同,它打印实际精度而不是默认精度。
因此,我们可以制作一个简单的实用函数
float_to_str:
import decimal# create a new context for this taskctx = decimal.Context()# 20 digits should be enough for everyone :Dctx.prec = 20def float_to_str(f): """ Convert the given float to a string, without resorting to scientific notation """ d1 = ctx.create_decimal(repr(f)) return format(d1, 'f')
必须注意不要使用全局十进制上下文,因此将为此函数构造一个新的上下文。这是最快的方法。另一种方法是使用
decimal.local_context它,但是会比较慢,为每次转换创建一个新的线程本地上下文和一个上下文管理器。
现在,此函数返回带有尾数所有可能数字的字符串,四舍五入为最短的等效表示形式:
>>> float_to_str(0.1)'0.1'>>> float_to_str(0.00000005)'0.00000005'>>> float_to_str(420000000000000000.0)'420000000000000000'>>> float_to_str(0.000000000123123123123123123123)'0.00000000012312312312312313'
最后的结果四舍五入到最后一位
正如@Karin所指出的,
float_to_str(420000000000000000.0)与所期望的格式不完全匹配;它返回
420000000000000000而没有尾随
.0。



