python - Python - 在打印语句中将浮点数显示为小数
问题描述
我正在查看低资本加密货币模因硬币的价格。我想在打印语句中格式化并显示为小数,大约 10 位数。例如,CoinGekco 上显示的埼玉价格为 0.000000100861 美元。
我不明白我是否使用错误的十进制库,或者这只是一个打印/格式问题。
from decimal import Decimal
# I think everything after the 7663 is irrelevant, this is a number I'm getting back
# from a Uniswap API. It could be the price in ETH, that is my next issue.
price_float = 2.08229530000000007663121204885725199461299350645049344166181981563568115234375E-11
price_decimal = Decimal(str(price_float))
print("float:", price_float)
print("decimal:", price_decimal)
结果:
float: 2.0822953e-11
decimal: 2.0822953E-11
期望的结果:
float: 2.0822953e-11
decimal: .000000000020822953
但是,如果我尝试使用小于 6 的指数,它似乎可以工作:
price_float = 2.08229530000000007663121204885725199461299350645049344166181981563568115234375E-6
结果:
decimal: 0.0000020822953000000003
更新 1 - 基于评论/建议:尝试格式化字符串。所以改变我的问题,只要我不添加数字或者对它们进行数学运算,我是否需要打扰小数?
print("float: {:10.14f}".format(price_float))
print("decimal: {:10.14f}".format(price_decimal))
结果:
float: 0.00000208229530
decimal: 0.00000208229530
解决方案
我这样做
print(f'{price_float:.20f}')
print(f'{price_float:.20E}')
输出
0.00000000002082295300
2.08229530000000007663E-11
推荐阅读
- android - 如何通过 Kotlin 中的 gson 访问嵌套 JSON 中的值?
- powershell - 在 Oneliner 中的 ConvertFrom-StringData 之后删除重复项
- django - 如何在没有完全关闭的情况下在 Django 服务器中执行实时应用程序更新?
- php - 我正在尝试将文件上传到正在开发的网站的数据库,但出现错误
- react-native - React Navigation 5 的问题:底部选项卡导航器未正确渲染,显示带阴影的小框
- angular - Angular 谷歌地图 AGM 方向 | 看不到路线信息
- r - dplyr 用良好值的函数替换新列中的 NA
- react-native - useState 无法更新 WebSocket 的 onmessage 事件中的数组
- algorithm - 查找多组数字之间的交集的最有效方法
- javascript - 使用 javascript 从 HTML 日期选择器中获取正确的日期