Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the sum of a float of numbers?

I have 0.0 24.0 0.0 12.0 0.0 0.0 0.0 0.0 0.0 how do i get the sum of these values? .sum etc do not work on floats

EDIT:

Im doing

<% @data.each do |data| %>
    <%= data[ :values ]%>
<%end%>

Where data[:values] prints [5.0, 0.0, 0.0, 0.0, 0.0] [4.0, 0.0, 0.0, 0.0, 0.0] [1.0, 0.0, 0.0, 0.0, 0.0] and i only want to get the first value of each array and sum them together to get 10.0

@data prints

[{:name=>"BMW", :values=>[0.0, 0.0, 0.0, 0.0, 0.0]}, {:name=>"Asda", :values=>[32.0, 12.0, 0.0, 0.0, 0.0]}]
like image 685
ahmet Avatar asked Jan 19 '23 10:01

ahmet


1 Answers

Assuming they are in an array, this works:

irb(main):001:0> [0.0, 1.0, 3.0].inject(:+)
=> 4.0

Edit: from your edited question, it appears you want:

@data.reduce(0) { |sum, x| sum += x[:values][0] }

Which grabs the first (0th) element of each :values, and sums them all together:

irb(main):003:0> @data
=> [{:values=>[0.0, 0.0, 0.0, 0.0, 0.0], :name=>"BMW"}, {:values=>[32.0, 12.0, 0.0, 0.0, 0.0], :name=>"Asda"}]
irb(main):004:0> @data.reduce(0) { |sum, x| sum += x[:values][0] }
=> 32.0
like image 158
derobert Avatar answered Jan 24 '23 17:01

derobert