Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate float number using precision in python [duplicate]

Tags:

python

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.

like image 238
mateatdang Avatar asked Feb 21 '26 13:02

mateatdang


1 Answers

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
like image 99
U12-Forward Avatar answered Feb 24 '26 04:02

U12-Forward