The problem is that Decimal(1.2225) is not what you expect it to be:
>>> Decimal(1.2225)
Decimal('1.2224999999999999200639422269887290894985198974609375')
You are using a float to the create the decimal, but that float is already too imprecise for your use case. As you can see, it’s actually a 1.222499 so it is smaller than 1.2225 and as such would correctly round down.
In order to fix that, you need to create decimals with correct precision, by passing them as strings. Then everything works as expected:
>>> x = Decimal('1.2225')
>>> x.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.223')
>>> y = Decimal('1.2224')
>>> y.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.222')
Answer from poke on Stack OverflowThe problem is that Decimal(1.2225) is not what you expect it to be:
>>> Decimal(1.2225)
Decimal('1.2224999999999999200639422269887290894985198974609375')
You are using a float to the create the decimal, but that float is already too imprecise for your use case. As you can see, it’s actually a 1.222499 so it is smaller than 1.2225 and as such would correctly round down.
In order to fix that, you need to create decimals with correct precision, by passing them as strings. Then everything works as expected:
>>> x = Decimal('1.2225')
>>> x.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.223')
>>> y = Decimal('1.2224')
>>> y.quantize(Decimal('0.001'), ROUND_HALF_UP)
Decimal('1.222')
Here are three solution in this link, I hope this would help you exactly what you want to do. https://gist.github.com/jackiekazil/6201722
from decimal import Decimal
# First we take a float and convert it to a decimal
x = Decimal(16.0/7)
# Then we round it to 2 places
output = round(x,2)
# Output to screen
print output
Videos
How to use round function in Python with decimal places?
How to round numbers in pandas using Python round function?
What is the Python round function?
Python includes the round() function which lets you specify the number of digits you want. From the documentation:
round(x[, n])Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).
So you would want to use round(x, 2) to do normal rounding. To ensure that the number is always rounded up you would need to use the ceil(x) function. Similarly, to round down use floor(x).
from math import ceil
num = 0.1111111111000
num = ceil(num * 100) / 100.0
See:
math.ceil documentation
round documentation - You'll probably want to check this out anyway for future reference