I am working on python 2.7. I want to fix the number of decimal places in a number written in scientific notation like 1.32e6, but instead of using for example "%3f". I want to write something like:
n=3
"%.nf"
where n is the number of decimal places, but it can be changed from my application.
n = 4
print("{0:.{1}f}".format(1.987213,n))
n = 5
print("{0:.{1}f}".format(1.987213,n))
Output
1.9872
1.98721
i = 123456789
n = 3
print('{:.{n}e}'.format(i, n=n))
Output:
'1.235e+08'
You can try this,
>>> a = 10e6
>>> n = 2
>>> '%.{}f'.format(n) % a
'10000000.00'
Or cast to float,
>>> a = 10e6
>>> n = 2
>>> float('%.{}f'.format(n) % a)
10000000.0
If you want to return to scientific notation,
>>> a = 103.023232
>>> n = 3
>>> '%.{}E'.format(n) % a
'1.030E+02'
The old printf
-style formatting operator supports this, though you'll probably want to use the newer format
method.
>>> n = 3
>>> "%.*f" % (n, 3.14159)
'3.142'
When you use *
as the precision, the value to use precedes the floating-point value in the tuple on the RHS.
Thank you every body for the answers. I tried the method of Ajay Dabas and that worked for me perfectly. This example is going to be used in a major (but easy) application. The complete code with the improved solution is:
enter code here
entrada_n= "Ingrese n:" enter code here
n= input (entrada_n)
enter code here
entrada_numero="Ingrese numero:" enter code here
numero=input(entrada_numero)
enter code here
print("{0:.{1}f}".format(numero,n)) enter code here
print("{0:.{1}e}".format(numero,n))
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.