how to calculate float number using precision in python

Viewed 75
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.

4 Answers

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 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 quantize method of decimal library

from decimal import Decimal


result = Decimal('31684.26999999999883584657356').quantize(Decimal('0.01'))
# result = Decimal('31684.27')
Related