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'
Related
This question already has an answer here:
Is Python's Decimal class variable width?
(1 answer)
Closed 1 year ago.
How to sum these two large strings, if I transform to FLOAT it loses the accuracy.
str1= '5.123654879542658'
str2= '8.777548795426584'
str(float(string1) + float(string2))
The decimal package is for high precision (28 places by default) maths:
>>> from decimal import Decimal
>>> str1= '5.123654879542658'
>>> str2= '8.777548795426584'
>>> Decimal(str1) + Decimal(str2)
Decimal('13.901203674969242')
Update: #KarlKnechtel seems to have found a close duplicate, oh well...
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')
This question already has answers here:
Python float to int conversion
(6 answers)
Closed 8 years ago.
In my original code I was trying to compute some indices out of some float values and I faced the following problem:
>>> print int((1.40-.3)/.05)
21
But:
>>> print ((1.40-.3)/.05)
22.0
I am speechless about what is going on. Can somebody please explain?
This is caused by floating point inaccuracy:
>>> print repr((1.40-.3)/.05)
21.999999999999996
You could try using the Decimal type instead:
>>> from decimal import Decimal
>>> Decimal
<class 'decimal.Decimal'>
and then
>>> (Decimal('1.40') - Decimal('.3')) / Decimal('.05')
Decimal('22')
The fractions.Fraction class would work too. Or, you could just round:
>>> round((1.40-.3)/.05, 10) # round to 10 decimal places
22.0
Drop the print and you'll see that the actual value is:
>>> (1.40-.3)/.05
21.999999999999996
Python 2 print() (more accurately, float.__str__) lies to you by rounding to a couple of decimal digits. Python 3 print() (again, actually float.__str__) doesn't do that, it always gives a faithful representation of the actual value (it abbreviates, but only when it doesn't change the value).
This inaccuracy is inherent to floating point numbers (including Decimal, though its inaccuracies occur different cases). This is a fundamental problem, representing arbitrary real numbers is not possible. See Is floating point math broken? for explanations.
I think this explains it straightforwardly:
import decimal
>>> (decimal.Decimal(1.40) -decimal.Decimal(.3))/decimal.Decimal(.05)
Decimal('21.99999999999999722444243843')
>>> (decimal.Decimal('1.40') -decimal.Decimal('.3'))/decimal.Decimal('.05')
Decimal('22')
This question already has answers here:
Python rounding error with float numbers [duplicate]
(2 answers)
Python weird addition bug [duplicate]
(4 answers)
Closed 9 years ago.
I'm trying to add decimal numbers a decimal number and it works correctly but when I do 1.1 + 0.1 I get 1.2000000000000002 but all I want it to equal to is 1.2. When I do 1.0 + 0.1 I get 1.1 which is perfect but i don't get that for 1.1 + 0.1. So is there a way that I can get rid of the 000000000000002 from 1.2000000000000002?
Thanks.
As has been stated countless times, 0.1 cannot be represented exactly in IEEE 754 floating point. You can read all about why in What Every Computer Scientist Should Know About Floating-Point Arithmetic or The Floating Point Guide
You can trucate or round the value:
>>> round(1.1+.1,2)
1.2
>>> "%.*f" % (1, 1.1+.1 )
'1.2'
>>> s=str(1.1+.1)
>>> s[0:s.find('.')+2]
'1.2'
If you want exact representation of those values, consider using the Decimal module:
>>> import decimal
>>> decimal.Decimal('1.1')+decimal.Decimal('.1')
Decimal('1.2')
Note that you need to start with the string representation of your float, '0.1' since 0.1 is not exactly representable in binary in IEEE floating point:
>>> decimal.Decimal(.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
To then get a string representation back after you calculate, you can use str:
>>> str(sum(map(decimal.Decimal,['.1','.1','.5','.5'])))
'1.2'
Another alternative is to use a rational number library such as Fractions:
>>> from fractions import Fraction as Fr
>>> Fr(11,10)+Fr(1,10)
Fraction(6, 5)
With that result, you will still need to round, truncate, or use an arbitrary precision arithmetic package to get an exact number (depending on the inputs...)
You can try string formatting, documentation here.
>>> "%0.2f" % float(1.1 + 0.1)
'1.20'
Or Even:
>>> "%0.1f" % float(1.1 + 0.1)
'1.2'
As to why, it is explicitly described on PEP 327 here.
This is the literal answer to your question:
float(str(1.1 + 0.1)[0:3])
If you're interested in the "why" of the problem then refer to the links provided in the question comments.
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!