2

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)

Subash
  • 3,128
  • 6
  • 30
  • 44
Jake Metz
  • 65
  • 9
  • See [ruby round off to two decimal place and keep zero](https://stackoverflow.com/questions/33802099/ruby-round-off-to-two-decimal-place-and-keep-zero) – assefamaru Mar 14 '18 at 05:16
  • 1
    You shouldn't use floats for monetary values. – Stefan Mar 14 '18 at 07:22
  • @Stefan why not? If we collect all the small inaccuracies in floating point math as currency we could be rich :) – engineersmnky Mar 14 '18 at 14:46
  • @stefan thank you for the insight. I have now covered that topic and will not be using float to reflect monetary value. – Jake Metz Mar 30 '18 at 00:27

2 Answers2

4

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 !

Ashik Salman
  • 1,819
  • 11
  • 15
  • This one did the trick!! Thank you for the help. I'm just starting out in this programming path and I was able to burn this off my backlog – Jake Metz Mar 14 '18 at 05:54
0

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}
Shani
  • 2,433
  • 2
  • 19
  • 23
  • unfortunately this still returns the total cost as 23.0 and not 23.00 as I wanted. Thank you for your reply however – Jake Metz Mar 14 '18 at 05:53