This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 2 years ago.
precision = 2
number = 31684.28
result = Decimal(number) - Decimal(10 ** -precision)
print(result)
Desired output:
31684.27
Actual output:
31684.26999999999883584657356
What I try to do is to subtract 0.01 from number.
You have to make the values with Decimal(...) not the output. So try this:
from decimal import Decimal
precision = 2
number = 31684.28
result = number - float(10 ** Decimal(-precision))
print(result)
Output:
31684.27
You should use formating like the following:
print("{:.2f}".format(result))
Or using round like:
print(round(result, 2))
comment
The question wasn't clear from the start. The correct answer (in my opinion is of #U11-Forward)
You can use the function round
The syntax is: round(number, digits)
So, result = round(number, 2)
You can read more about it here: https://www.w3schools.com/python/ref_func_round.asp
You can use quantize method of decimal library
from decimal import Decimal
result = Decimal('31684.26999999999883584657356').quantize(Decimal('0.01'))
# result = Decimal('31684.27')
Related
This question already has answers here:
Is floating point arbitrary precision available?
(5 answers)
Is floating point math broken?
(31 answers)
Closed 1 year ago.
I am trying to divide floats by each other but am having a hard time getting accurate results. I understand that computers store floats in a way where the value stored is not exact to the given number. I am simply looking for a way where I can get specific results when working with floats.
input:
x = 2.4
y = 0.2
print(x/y)
Output:
11.999999998
I highly recommend to use decimals
Example
from decimal import Decimal
x = Decimal("2.4")
y = Decimal("0.2")
print(x / y) # 12
Notice we passing number as string, as passing float numbers would have the same problem you pointed out.
But care with comparison, as 12 == x / y evaluates to False
This question already has answers here:
How to get numbers after decimal point?
(37 answers)
Closed 1 year ago.
I'm having a hard time doing this I have tried experimenting with (0:.2f)
I want the program to only print the decimal part
Example inputs and outputs
Inputs
100.56
455.345
89.5
Outputs
.56
.345
.5
Is there a way to do this?
you may try the code as below
input = 100.56
print(input % 1)
you could refer to the answer at How to get numbers after decimal point?
If you want to have only the original decimal part, you can do :
inputFloat = 25189456.1584566
decimalPart = '.' + str(inputFloat).split('.')[1]
print(decimalPart)
Something like this should work
def f(x, decimals=2):
r = str(round(x, decimals)) #round and convert to string
r = r.split('.')[-1] #split at the dot and keep the decimals
r = '.' + r #add the dot
return r
f(100.56789) #.57
[f(x) for x in [100.56, 455.345, 89.5]] #['.56', '.35', '.5']
The one-liner would be '.' + str(round(x, 2)).split('.')[-1] or f".{str(round(x, 2)).split('.')[-1]}" where x is the float you are interested in.
This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 6 years ago.
I am trying to do the calculation
Using the python decimal module with the following code:
from decimal import *
getcontext().prec = 9
sum = Decimal(0)
for i in range(1,11):
sum += Decimal(1/(i**4))
print sum
however, this outputs 1, not a very small fraction like I would expect. I can't find much information here https://docs.python.org/2/library/decimal.html about what is wrong with the code. My guess is sum is not being used as a Decimal in the loop, but I am unsure how to resolve that.
If you use Python 2.x, then in the expression: 1/(i**4), the integer devision is used, as result for i=1, it equals to 1 and for all other i>1, it gets 0.
Just add floating point to 1: 1./(i**4), this should fix the problem.
PS In Python 3.x, your code should work as expected, because operator / is defined on floating point numbers, while operator // is defined for integers.
First of all, don't use sum as a variable name, as it is a built-in.
And its sort of necessary to provide at least one float for arithmetic if you expect a float-type answer, here:
s = Decimal(0)
for i in range(1,11):
s += Decimal(1./(i**4)) # dividing 1. or 1.0 instead of just 1
print s
this gives:
1.08203658
This question already has answers here:
Python rounding error with float numbers [duplicate]
(2 answers)
Closed 6 years ago.
Can someone tell me what I'm missing here? This is using Python 2.7.11:
print float(148.95)
print float(148.95)*100
print int(float(148.95)*100)
Why does this print:
148.95
14895.0
14894 <--- Shouldn't this be 14895?
148.95 is not a number that can be exactly represented using floating point. The number internally stored is actually 148.94999999999998863131622783839702606201171875. When you multiply by a hundred, you get 14894.999999999998181010596454143524169921875. When you convert that to integer, it cuts off the .999... and you're left with 14894.
If you want a data type that can exactly represent numbers with at least two decimal places of precision, consider using Decimal.
>>> from decimal import Decimal
>>> x = Decimal("148.95")
>>> print x
148.95
>>> print x*100
14895.00
>>> print int(x*100)
14895
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!