编程语言
首页 > 编程语言> > python小数格式:不用科学计数法、不截断

python小数格式:不用科学计数法、不截断

作者:互联网

对于一个小数,如 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

  1. How to suppress scientific notation when printing float values?
  2. Formatting floats without trailing zeros

标签:0.0000000000001,format,python,float,计数法,1e,print,0.0001,小数
来源: https://blog.csdn.net/HackerTom/article/details/121990415