3
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.

David
  • 8,113
  • 2
  • 17
  • 36
mateatdang
  • 31
  • 5

4 Answers4

3

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)

David
  • 8,113
  • 2
  • 17
  • 36
3

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
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

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

Virej Dasani
  • 185
  • 3
  • 15
1

You can use quantize method of decimal library

from decimal import Decimal


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