Search code examples
pythonpython-2.7sqlitecurrency

Adding a tax rate to a base price in Python and rounding to 0 or 5 cents


I have a datamodel (sqlite3 database field) where prices are stored like this:

base_price1 = 3715
base_price2 = 1000

Which actually represents

$37.15
$10.00

I have followed that convention based on several recommendations found in forums (ex. https://dba.stackexchange.com/questions/15729/storing-prices-in-sqlite-what-data-type-to-use).

Now I have a tax rate stored the same way:

tax = 2100

where tax is actually

21.00%

I would like to work out the final price and round to 0 or 5 cents.

So

$37.15 * 1.21 = $44.9515

So the final value to be stored would need to be:

4495

Which would be the pythonic/simplest way to implement this in Python2.7?


Solution

  • For the rounding, you can use:

    def round_to_0_or_5(i):
        return int((5 * round((i/5.),0)))
    
    for i in [3445, 5550, 4442, 4443]:
        print(i, "-->", round_to_0_or_5(i))
    
    # 3445 --> 3445
    # 5550 --> 5550
    # 4442 --> 4440
    # 4443 --> 4445
    

    (works on both Python 2.7 and Python 3)