Python - 在打印语句中将浮点数显示为小数
Python - show float as a decimal in a print statement
我正在查看低资本加密模因硬币的价格。我想在打印语句中格式化并显示为小数,大约 10 位数字。例如,CoinGekco 上显示的 Saitama 价格为 $0.000000100861.
我不明白是我使用的 Decimal 库有误,还是这只是一个 print/formatting 问题。
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 - 基于 comment/suggestion:尝试格式化字符串。
所以改变我的问题,只要我不加数字或者对它们做数学运算,我是否需要为小数烦恼呢?
print("float: {:10.14f}".format(price_float))
print("decimal: {:10.14f}".format(price_decimal))
结果:
float: 0.00000208229530
decimal: 0.00000208229530
您可能正在寻找类似 print("{:12.10f}".format(price_decimal))
的内容。这里的输出格式不受十进制库控制
我这样做
print(f'{price_float:.20f}')
print(f'{price_float:.20E}')
输出
0.00000000002082295300
2.08229530000000007663E-11
我正在查看低资本加密模因硬币的价格。我想在打印语句中格式化并显示为小数,大约 10 位数字。例如,CoinGekco 上显示的 Saitama 价格为 $0.000000100861.
我不明白是我使用的 Decimal 库有误,还是这只是一个 print/formatting 问题。
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 - 基于 comment/suggestion:尝试格式化字符串。 所以改变我的问题,只要我不加数字或者对它们做数学运算,我是否需要为小数烦恼呢?
print("float: {:10.14f}".format(price_float))
print("decimal: {:10.14f}".format(price_decimal))
结果:
float: 0.00000208229530
decimal: 0.00000208229530
您可能正在寻找类似 print("{:12.10f}".format(price_decimal))
的内容。这里的输出格式不受十进制库控制
我这样做
print(f'{price_float:.20f}')
print(f'{price_float:.20E}')
输出
0.00000000002082295300
2.08229530000000007663E-11