Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – show float as a decimal in a print statement

I’m looking at prices of low-capitalization crypto meme coins. I want to format and show as a decimal in the print statement, up about 10 digits. For example, the price of Saitama as shown on CoinGekco is $0.000000100861.

I don’t understand if I’m using the Decimal library wrong, or if this is just a print/formatting issue.

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)

Results:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

float: 2.0822953e-11
decimal: 2.0822953E-11

Desired Results:

float: 2.0822953e-11
decimal: .000000000020822953 

But if I try an exponent less than 6 it seems to work:

price_float = 2.08229530000000007663121204885725199461299350645049344166181981563568115234375E-6

Result:

decimal: 0.0000020822953000000003

Update 1 – based on comment/suggestion: Trying the formatting string.
So a change to my question, do I need to bother with decimal at all, as long as I’m not adding numbers or maybe doing math on them?

print("float: {:10.14f}".format(price_float))
print("decimal: {:10.14f}".format(price_decimal))

Result:

float: 0.00000208229530
decimal: 0.00000208229530

>Solution :

I do that

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

Output

0.00000000002082295300
2.08229530000000007663E-11
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading