简体   繁体   中英

How to print decimal notation rather than scientific notation in Python?

Assume to have this number:

p=0.00001

Now, if we print this variable we get 1e-05 (ie, that number in scientific notation). How can I print exactly 0.00001 (ie, in decimal notation)? Ok, I know I can use format(p, '.5f') , but the fact is that I don't know in advance the number of decimal digits (eg, I may have 0.01 or 0.0000001 , etc.). Therefore, I could count the number of decimal digits and use that in the format function. In doing so, I have a related problem... is there any way to count the decimal digits of a decimal number without using Decimal ?

... is there any way to count the decimal digits of a float number without using Decimal ?

Nope. And there isn't any way to do it using Decimal either. Floating point numbers that aren't an exact sum of powers of 1/2 don't have an exact number of decimal places. The best you can do is perform some sort of guesstimate based on the leftmost non-zero digit and some arbitrary count of digits.

In general you can't count the number of decimal digits, but you can compute the minimum precision and use it with f format specification in str.format or equivalent function:

from math import ceil, log10
p = 0.00001
precision = int(ceil(abs(log10(abs(p))))) if p != 0 else 1
'{:.{}f}'.format(p, precision)

You'll need to increase precision if you want to display more than one significant digit. Also you might need a slightly different logic for numbers > 1.

As of Python 3.6.x and above versions, f-strings are a great new way to format strings. Not only are they more readable, more concise, and less prone to error than other ways of string formatting.
You can read more about f-strings on https://datagy.io/python-f-strings/

Coming to your question,

number = 0.00001    # 1e-5
print(f"{number:f}")

output:

0.000010

This also works directly eg

number = 1e-5
print(f"{number:f}")

output:

0.000010

But this method can show you digits up to 1e-06
for example

number = 0.000001    # 1e-6
print(f"{number:f}")

output:

0.000001

which works but if you go further

number = 0.0000001    # 1e-7
print(f"{number:f}")

output:

0.000000

So be careful using this.

p = 0.0000000000000000000001

s = str(p)

print(format(p, "." + s.split("e")[-1][1:]+"f")) if "e" in s else print(p)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM