This question already has answers here:
How to suppress scientific notation when printing float values?
(16 answers)
Closed 7 months ago.
The community reviewed whether to reopen this question 5 months ago and left it closed:
Original close reason(s) were not resolved
I have numbers in a file (so, as strings) in scientific notation, like:
8.99284722486562e-02
but I want to convert them to:
0.08992847
Is there any built-in function or any other way to do it?
I'm pretty sure you can do this with:
float("8.99284722486562e-02")
# and now with 'rounding'
"{:.8f}".format(float("8.99284722486562e-02"))
I'm making this answer since the top voted one has misinformation and so i can explain my improvements.
TL;DR: Use ("%.17f" % n).rstrip('0').rstrip('.')
By default Python formats to scientific notation if there's 5 or more zeroes at the beginning.
0.00001 / 1e-05 formats to "1e-05".
0.0001 / 1e-04 formats to "0.0001".
So of course 8.99284722486562e-02 will format to "0.0899284722486562" already.
A better example would've been 8.99284722486562e-05. (0.00008992847224866)
We can easily format to raw decimal places with "%f" which is same as "%.6f" by default.
"%f" % 8.99284722486562e-05 produces '0.000090'.
"%f" % 0.01 produces '0.010000'.
By default floats display upto 17 decimal places.
0.1234567898765432123 - (19 dp input)
0.12345678987654321 - (17 dp output)
So if we did "%.17f" % 8.99284722486562e-02 we'd get '0.08992847224865620'. (note the extra 0)
But if we did "%.17f" % 0.0001 we surely wouldn't want '0.00010000000000000'.
So to remove the trailing zeroes we can do: ("%.17f" % n).rstrip('0').rstrip('.')
(Notice we also strip the decimal point incase the number has no fraction left)
Also there's counterparts to %f:
%f shows standard notation
%e shows scientific notation
%g shows default (scientific if 5 or more zeroes)
The scientific notation can be converted to a floating point number with float.
In [1]: float("8.99284722486562e-02")
Out [1]: 0.0899284722486562
The float can be rounded with format and then float can be used on the string to return the final rounded float.
In [2]: float("{:.8f}".format(float("8.99284722486562e-02")))
Out [2]: 0.08992847
2022 edit for No Sound's comment:
I learned this solution from here (archived)
The following solutions work for larger numbers.
Solution 1)
import numpy as np
print(np.format_float_positional(1.32456e-12, trim='-'))
print(np.format_float_positional(1.32456e-24, trim='-'))
print(np.format_float_positional(1.32456e12, trim='-'))
print(np.format_float_positional(1.32456e24, trim='-'))
# Output: 0.00000000000132456
# 0.00000000000000000000000132456
# 1324560000000
# 1324560000000000000000000
Solution 2)
same as above accept this time using a lambda function
import numpy as np
pretty_print = lambda x: np.format_float_positional(x, trim="-")
print(pretty_print(1.32456e-12))
print(pretty_print(1.32456e-24))
print(pretty_print(1.32456e12))
print(pretty_print(1.32456e24))
# Output: 0.00000000000132456
# 0.00000000000000000000000132456
# 1324560000000
# 1324560000000000000000000
As you may know floating point numbers have precision problems. For example, evaluate:
>>> (0.1 + 0.1 + 0.1) == 0.3
False
Instead you may want to use the Decimal class. At the python interpreter:
>>> import decimal
>>> tmp = decimal.Decimal('8.99284722486562e-02')
Decimal('0.0899284722486562')
>>> decimal.getcontext().prec = 7
>>> decimal.getcontext().create_decimal(tmp)
Decimal('0.08992847')
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 6 months ago.
I want to do operations like
500.55%10 and get a value of 0.55 in return.
But instead Python sometimes returns 0.5500000000000114 for example (which in terms of magnitude is basically the same), I'm guessing this is because of the numerical way these calculations are done.
When I input a value like 500.55 I want it to be seen as 500.55000000000000.... with an infinite amount of zeros. So basically I want to get rid of ...00114 at the end.
print(500.55%10)
0.5500000000000114
Thanks.
Try the decimal module:
>>> from decimal import Decimal
>>> float(Decimal('500.55') % 10)
0.55
Documentation here.
you can use the round function to round. Alternatively you need to use the decimal module which handles extra decimals in the way that you ask...
here are both methods:
import decimal
# normal way
print('normal way:', 500.55%10)
# do some rounding
print('rounding:', round(500.55%10, 10) )
# use the decimal
decimal.getcontext().prec = 10
print('decimal module:', decimal.Decimal(500.55)%decimal.Decimal(10))
result:
normal way: 0.5500000000000114
rounding: 0.55
decimal module: 0.5500000000
you can use the built-in decimal module and their decimal.Decimal object.
decimal.Decimal(value='0', context=None)
from the documentation:
Construct a new Decimal object based from value.
value can be an integer, string, tuple, float, or another Decimal object. If no value is given, returns Decimal('0'). If value is a string, it should conform to the decimal numeric string syntax after leading and trailing whitespace characters, as well as underscores throughout, are removed
Example implementation:
>>> import decimal
>>> float(decimal.Decimal('500.55') % 10)
0.55
This question already has answers here:
Python Decimals format
(6 answers)
Closed 3 years ago.
I have a python program which takes some floating type values and writes to a file.
I round these numbers to 6 decimal places and then convert to a string type before writing to file.
file.write(str(round(value,6)))
However with certain numbers the value written to file is in the format shown below.
e.g. 3e-06 or 4e-03
How can I avoid this and instead write out in decimal format like
0.000003 and 0.004000
How can I print exactly 6 figures after the decimal point.
You can use the f-string f'{value:.6f}'.
Example:
value = 0.234
print(f'{value:.6f}')
value = 1
print(f'{value:.6f}')
value = 0.95269175
print(f'{value:.6f}')
Output:
0.234000
1.000000
0.952692
Also, in the answer linked in a comment, there was reference to :g. That can work, but probably not in this situation, because g may print scientific notation where appropriate, and discards insignificant zeroes. Consider a slightly modified example using g:
value = 0.234
print(f'{value:.6g}')
value = 1
print(f'{value:.6g}')
value = 0.000000000095269175
print(f'{value:.6g}')
Output:
0.234
1
9.52692e-11
You can also use basic string formatting:
a = 3e-06
# Outputs 0.000003
print('%.6f' % a)
# Outputs 0.000003000000
print('%.12f' % a)
This question already has answers here:
How to format a floating number to fixed width in Python
(10 answers)
Closed 7 years ago.
So I need to cut off some decimals cases in my output.
I have the following line:
print ("O valor a pagar é de ", ***float(n3)*1.3***, " euros.")
In the area that I highlited I get to much cases... The output is something like this for example: 2,47893698236923 and I want it to show only 2 decimal cases like: 2,47.
How do I do it? And I'm using python 3.5.0
As pointed out by BlivetWidget, floating format causes rounding not truncating.
You can use the Decimal module :
from decimal import Decimal, ROUND_DOWN
x = 2.47893698236923
print(Decimal(str(x)).quantize(Decimal('.01'), rounding=ROUND_DOWN))
print(Decimal(str(x)).quantize(Decimal('.001'), rounding=ROUND_DOWN))
output :
2.47
2.478
EDIT
As the Python docs explains :
The quantize() method rounds a number to a fixed exponent. This method
is useful for monetary applications that often round results to a
fixed number of places
EDIT 2
See also Truncating floats in Python
Use the round() function.
print("O valor a pagar é de ", round(float(n3) * 1.3, 2), " euros.")
Based on the example you gave, you want to truncate a value (the other answers at this time will round the value). If you just want to truncate, I would use a string slice.
>>> num = 2.47893698236923
>>> str(num)[:str(num).find('.') + 3]
'2.47'
PS: if you don't know if there will be a decimal in there, you could use this variant:
>>> numstr = str(num)
>>> numstr[:(numstr.find('.') + 3) if numstr.find('.') else None]
'2.47'
This question already has answers here:
How to print float to n decimal places including trailing 0s?
(5 answers)
Closed 7 years ago.
I am approximating phi to 50 decimal places and want to return the value I have computed. I do not want to print it otherwise I can't use it in calculations.
How can I do this because python only wants to display 11 decimal places or something like that?
Thanks
python floats do not have that precision. you need to use python decimal:
from decimal import getcontext, Decimal
getcontext().prec = 50
print(Decimal(1) / Decimal(7))
the drawback is that calculations with these will take much more time than the ones with float.
This question already has answers here:
Limiting floats to two decimal points
(35 answers)
Closed 5 months ago.
I am reading a text file with floating point numbers, all with either 1 or 2 decimal points. I am using float() to convert a line into a float, and raising a ValueError if that fails. I am storing all floats in a list. When printing it out, I'd like to print it out as a 2 decimal places floating point.
Assume I have a text file with the numbers -3.65, 9.17, 1. I read each one, and once I convert them to float and append them to a list. Now in Python 2, calling float(-3.65) returns -3.65. In Python 3 however, float(-3.65) returns -3.6499999999999999 which loses its precision.
I want to print the list of floats, [-3.6499999999999999, 9.1699999999999999, 1.0] with 2 decimal points only. Doing something along the lines of '%.1f' % round(n, 1) would return a string. How can I return a list of all two decimal points of floats, and not strings? So far, I rounded it using [round(num, 2) for num in list] but would need to set the decimal points / precision instead of round().
The comments state the objective is to print to 2 decimal places.
There's a simple answer for Python 3:
>>> num=3.65
>>> "The number is {:.2f}".format(num)
'The number is 3.65'
or equivalently with f-strings (Python 3.6+):
>>> num = 3.65
>>> f"The number is {num:.2f}"
'The number is 3.65'
As always, the float value is an approximation:
>>> "{}".format(num)
'3.65'
>>> "{:.10f}".format(num)
'3.6500000000'
>>> "{:.20f}".format(num)
'3.64999999999999991118'
I think most use cases will want to work with floats and then only print to a specific precision.
Those that want the numbers themselves to be stored to exactly 2 decimal digits of precision, I suggest use the decimal type. More reading on floating point precision for those that are interested.
The simple way to do this is by using the round buit-in.
round(2.6463636263,2) would be displayed as 2.65.
In a word, you can't.
3.65 cannot be represented exactly as a float. The number that you're getting is the nearest number to 3.65 that has an exact float representation.
The difference between (older?) Python 2 and 3 is purely due to the default formatting.
I am seeing the following both in Python 2.7.3 and 3.3.0:
In [1]: 3.65
Out[1]: 3.65
In [2]: '%.20f' % 3.65
Out[2]: '3.64999999999999991118'
For an exact decimal datatype, see decimal.Decimal.
Try this:
num = input("Please input your number: ")
num = float("%0.2f" % (num))
print(num)
I believe this is a lot simpler. For 1 decimal place use %0.1f. For 2 decimal places use %0.2f and so on.
Or, if you want to reduce it all to 2 lines:
num = float("%0.2f" % (float(input("Please input your number: "))))
print(num)
Try to understand through this below function using python3
def floating_decimals(f_val, dec):
prc = "{:."+str(dec)+"f}" #first cast decimal as str
print(prc) #str format output is {:.3f}
return prc.format(f_val)
print(floating_decimals(50.54187236456456564, 3))
Output is : 50.542
Hope this helps you!