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
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值