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
.
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 should use formating like the following:
print("{:.2f}".format(result))
Or using round
like:
print(round(result, 2))
The question wasn't clear from the start. The correct answer (in my opinion is of @U11-Forward)
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 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')