0

I am having trouble converting to a decimal float, and then rounding it up. the expected value is not correct.

I will greatly appreciate your help.

from decimal import Decimal, ROUND_HALF_UP         

def round_decimal(x):            
    return x.quantize(Decimal(".01"), rounding=ROUND_HALF_UP)

a=7.1450
b=(Decimal(a))

print (b)

b=7.144999999999999573674358543939888477325439453125

print(round_decimal(Decimal(a) ))

b=7.14 # 7.15 expected
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Giancarlo
  • 169
  • 11
  • Does this answer your question? [How do you round UP a number in Python?](https://stackoverflow.com/questions/2356501/how-do-you-round-up-a-number-in-python) – Trenton McKinney Jun 14 '20 at 21:41

1 Answers1

0

This is the expected behavior from the module, because by using decimal and ROUND_HALF_UP you will always lose a decimal value (from 7.15 to 7.14, or the decimal position you are rounding up to) if you wish to maintain the upper value, then you need to use ROUND_UP and NOT ROUND_HALF_UP:

def round_decimal(x):            
    return x.quantize(Decimal(".01"), rounding=ROUND_UP)
a = 7.1450
print(round_decimal(Decimal(a)))

Output:

7.15
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
  • hello, testing I have that a = 26.41, generates 26.42, expected value: 26.41 – Giancarlo Jun 14 '20 at 22:38
  • Also makes sense, because `ROUND_UP` will force the number to be rounded up regardless of the decimal position so if you have a 26.410 it will round to 26.42. `ROUND_HALF_UP` will round to 26.41 correctly. – Celius Stingher Jun 14 '20 at 22:44
  • hello the rounding of 7.144 should be 7.14 and the rounding of 7.1450 should be 7.15, all to two decimal places, it is rare that there is not much information. – Giancarlo Jun 15 '20 at 02:53