首页 > 解决方案 > 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

标签: pythondecimalpython-3.9

解决方案


我这样做

print(f'{price_float:.20f}')
print(f'{price_float:.20E}')

输出

0.00000000002082295300
2.08229530000000007663E-11

推荐阅读