How can I display 2 decimal places (padding) on a float even if the trailing number is a 0. So, if I sum only the :cost values in the example below I would like it to return 23.00
items = [
{customer: "John", item: "Soup", cost:("%.2f"% 8.50)},
{customer: "Sarah", item: "Pasta", cost:("%.2f"% 12.00)},
{customer: "John", item: "Coke", cost:("%.2f" % 2.50)}
]
PROBLEM: I have success displaying cost: values with two decimal places. However, the result returns a "string". I have tried ("%.2f" % 2.50).to_f with no such luck. I need a float so that I can complete the following inject code.
totalcost = items.inject(0) {|sum, hash| sum + hash[:cost]}
puts totalcost
When running this to sum the total cost I receive the following error because I cannot convert the string to a float successfully. String can't be coerced into Integer (TypeError)