Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rounding float up $.01 in python

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.

like image 647
Lance Collins Avatar asked Jan 08 '12 21:01

Lance Collins


2 Answers

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.

like image 81
unutbu Avatar answered Sep 28 '22 08:09

unutbu


if you want to write it in cents, you could use int(x*100+.5) to get cents integer from float dollars.

like image 23
Jakob Weisblat Avatar answered Sep 28 '22 07:09

Jakob Weisblat