'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
(i.e., that number in scientific notation). How can I print exactly 0.00001
(i.e., 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 (e.g., 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
?
Solution 1:[1]
p = 0.0000000000000000000001
s = str(p)
print(format(p, "." + s.split("e")[-1][1:]+"f")) if "e" in s else print(p)
Solution 2:[2]
... 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.
Solution 3:[3]
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.
Solution 4:[4]
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 e.g.
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Ignacio Vazquez-Abrams |
Solution 3 | |
Solution 4 | DharmanBot |