views:

81

answers:

5

Hello,

I just started programming in python not long ago, and I'm having trouble figuring out the rounding issue when it comes to tax and money. I can't seem to get decimals to always round up to the nearest hundredths place. for instance, in our state, sales takes is 9.5%, so a purchase of 5 dollars would make tax $.48, but in reality its $.475. I've tried math.ceil, but it seems like that only works to the nearest integer. Is there a simple way to enable a round up on any thousands digit? (ex .471 would round to .48)

Thanks

+1  A: 

To round to 2 digits, use round:

round(5*0.095,2)

EDIT: I see now that you wanted to round up. For that, I think you'll have to go with math.ceil(100*x)/100.

zvonimir
+2  A: 

You might want to rethink how you're representing your numbers. It might be best to represent all values as integers and then format them later when you need to print or display your output. This will give you the freedom of not worrying about floating-point errors and additionally will let you use math.ceil.

jlv
This is the answer I was about to post :) For clarity, scale everything to whole cents (so $1 = 100).
Zack
+5  A: 

For money amounts it is better to use Python's decimal, where you don't have problems with floating-point representation and the numbers will keep rounded to two decimals (cents).

import decimal

def calculateVat(price):
    VAT = decimal.Decimal('0.095')
    return (price * VAT).quantize(price, rounding=decimal.ROUND_UP)

price =  decimal.Decimal('5.00')

# calculateVat(price) returns:
# Decimal('0.48')
eumiro
+1  A: 

Doug Hellmann has an awesome blog called Python Module of the Week where he breaks down a module in the Python library in very clear detail. I think his post on the module math might be worth taking a look at: http://www.doughellmann.com/PyMOTW/math/

Tom
A: 

i think that fix is the thing you're looking for:

>>> from fpformat import fix
>>> fix('4.75', 1)
'4.8'
>>> fix('4.75', 2)
'4.75'
>>> fix('4.75', 3)
'4.750'
>>> 

then if you need to use it, you can use float()

Ant