I am working on a program that stores numbers as floats which I eventually write to a file as currency. I am currently using the round() function to round it to 2 decimals, but the business area would like me to round to the next penny no matter what the third decimal is. For example:
x = 39.142
In this case I am trying to get x to round up to 39.15. Obviously when I do the round function I get 39.14...
>>> round(x, 2)
39.14
Is there a way I can always round up to the next penny? I should mention that the numbers I am dealing with are printed to the file as currency.
Using the decimal module:
import decimal
D = decimal.Decimal
cent = D('0.01')
x = D('39.142')
print(x.quantize(cent,rounding=decimal.ROUND_UP))
# 39.15
Decimals have many options for rounding. The options and their meanings can be found here.
if you want to write it in cents, you could use int(x*100+.5) to get cents integer from float dollars.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With