snippetpythonMinor
Convert float price to integer price without commas
Viewed 0 times
withoutpriceconvertfloatintegercommas
Problem
My payment gateway wants the prices this way: "1050" instead of 10.50.
So I created this function:
https://repl.it/HgHI/3
Is there another way more elegant, or cleaner? I just want to improve.
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 -> 1016Is there another way more elegant, or cleaner? I just want to improve.
Solution
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)Code Snippets
def price_format_gateway(price):
return '{:.0f}'.format(100 * price)Context
StackExchange Code Review Q#162501, answer score: 6
Revisions (0)
No revisions yet.