6
\$\begingroup\$

My payment gateway wants the prices this way: "1050" instead of 10.50. So I created this function:

https://repl.it/HgHI/3

def price_format_gateway(price):
    price = "{0:.2f}".format(price)
    price = price.split(".")
    try:
      if len(price[1]) > 2:
        decimals = str(price[1][0:2])
      else:
        decimals = price[1]
    except IndexError:
      pass

    return str(price[0]) + str(decimals)


price_format_gateway(10) # Expected -> 1000
price_format_gateway(10.1) # Expected -> 1010
price_format_gateway(10.15765) # Expected -> 1016

Is there another way more elegant, or cleaner? I just want to improve.

\$\endgroup\$
4
\$\begingroup\$

When you want to round a number to a specific number of digits, instead use round. Here you can use round(price, 2). The string format performs this too, so, if you perform the string format to force two decimal places, you can get the number rounded to two decimals separated by a period. I.e 10.16. You then just want to remove the period, and so you can just use '10.00'.replace('.', ''), and so you can drastically simplify this to:

def price_format_gateway(price):
    return '{:.2f}'.format(price).replace('.', '')
\$\endgroup\$
6
\$\begingroup\$

For me at least, it would be more natural to think of the operation as a multiplication by 100:

def price_format_gateway(price):
    return '{:.0f}'.format(100 * price)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.