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.

200_success
146k22 gold badges190 silver badges478 bronze badges
asked May 4, 2017 at 14:03
\$\endgroup\$
0

2 Answers 2

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('.', '')
answered May 4, 2017 at 14:12
\$\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)
answered May 5, 2017 at 9:01
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.