3

Today I have a question for you about rounding up numbers using conditions in Python.

I am doing a sales website and my client wants to round up the prices depending of the result converting them from USD to Colombian Pesos. For example: 200 USD to COP results in 353990 COP, and it should be rounded to 359000.

He have implemented a function that is doing the trick in Excel:

=IF(F4>=10000000,(ROUNDUP(F4,-6)-100000),IF(F4>=1000000,(ROUNDUP(F4,-5)-10000),IF(F4>=100000,(ROUNDUP(F4,-4)-1000),IF(F4>=10000,(ROUNDUP(F4,-3)-1000),IF(F4>=0,(ROUNDUP(F4,-3)))))))

I need to do exact the same thing but in Python, and I don't know the way to do it.

Thanks for helping me!

Cristian Rojas
  • 2,746
  • 7
  • 33
  • 42
  • I'm not seeing why 353990 should be rounded to 359000 ... perhaps 354000, or 360000 ... – mgilson Jan 16 '13 at 20:19
  • Do you have some sort of datasource for conversion rates and significant digits for each supported currency? I doubt your client wants to round to the next 1000 when converting to Euros... – Silas Ray Jan 16 '13 at 20:23
  • @mgilson, I think the idea is to round the price so the last digit is a `9`, kind of like US prices that end in `.99`. – Mark Ransom Jan 16 '13 at 20:29

2 Answers2

5
import math
roundup = lambda x: math.ceil(x/1000.0) * 1000

Although rounding 353990 to 359000 makes no sense. This function will round 353990 up to 354000.

If you want normal rounding rather than a 'round up', you would just use the builtin funciton round:

round(x, -3)

and so for a generic roundup with the same function signature as round

def roundup(x, n=0):
    return math.ceil(x * (10**n)) * (10**-n)
forivall
  • 9,504
  • 2
  • 33
  • 58
2
def round_up(value, multiple):
    return multiple * math.ceil(float(value) / multiple)

def digits(value):
    return int(math.log(value, 10)) + 1

def round_price(value):
    if value < 10000:
        return int(round_up(value, 1000))
    d = digits(value)
    new_value = int(round_up(value, 10 ** (d - 2)))
    new_value -= 10 ** (d - 3)
    return new_value
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • @unutbu, I wasn't paying enough attention to the last term of the Excel formula. I'll have to make a minor fix to my answer. I think `ROUNDUP(100, -3)` would be the same as my `round_up(100, 1000)`. – Mark Ransom Jan 16 '13 at 21:00