Rounding floats to $ .01 in python

I am working on a program that stores numbers as floats, which I end up writing to a file as currency. I am currently using the round () function to round it to two decimal places, but in the business area, I would like to round to the next penny, regardless of the third decimal place. For instance:

x = 39.142

In this case, I'm trying to get x to round to 39.15. Obviously, when I do the round function, I get 39.14 ...

>>> round(x, 2)
    39.14

Is there a way that I can always round to the next penny? I should mention that the numbers I'm dealing with are printed to the file as a currency.

+5
source share
2 answers

:

import decimal
D = decimal.Decimal
cent = D('0.01')

x = D('39.142')
print(x.quantize(cent,rounding=decimal.ROUND_UP))
# 39.15

. .

+14

, int (x * 100 +.5), .

+1

All Articles