对于一个小数,如 0.0000000000001
,想得到相应的字符串,而不是转换为 1e-12
,可以用 numpy 的 format_float_positional
。
import numpy as np
a = 0.0001
b = 0.00001
c = 0.0000001
d = 0.0000000000001
print("{}, {}".format(a, b)) # 0.0001, 1e-05
print("{}, {:f}".format(a, b)) # 0.0001, 0.000010 <- 后者结尾多了个 0
print("{}, {}".format(str(a), str(b))) # 0.0001, 1e-05
print("{:.4f}, {:.4f}".format(a, b)) # 0.0001, 0.0000 <- 后者被截断
_a, _b, _c = "{:f}".format(a), "{:f}".format(b), "{:f}".format(c)
_a, _b, _c = _a.rstrip('0'), _b.rstrip('0'), _c.rstrip('0')
print(_a, _b, _c) # 0.0001 0.00001 0. <- c 精度不够,被截断
print(np.format_float_positional(c, trim='-')) # 0.0000001 <- 可以
print(np.format_float_positional(d, trim='-')) # 0.0000000000001 <- 可以
References
- How to suppress scientific notation when printing float values?
- Formatting floats without trailing zeros