Reputation: 97
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)
Upvotes: 2
Views: 3054
Reputation: 1879
You can calculate the sum of cost values after converting it to number(Integer/Float).
totalcost = items.map { |x| x[:cost].to_f }.sum
The value of totalcost
can be formatted with sprintf method in whatever way we want to display.
sprintf("%.2f", totalcost)
Hope it helps !
Upvotes: 4
Reputation: 2541
hash[:cost] is still returns a String. you could just cover it to a float before adding it to sum
totalcost = items.inject(0) {|sum, hash| sum + hash[:cost].to_f}
Upvotes: 0