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!
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)
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
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