I am trying to get my console to print out a summation of all my Locations rate card pricing.
I am trying to complete this task through the console but getting a BigDecimal as the result. Stuck on how to convert this result into a legible string or integer.
Results:
Location.pluck(:rate_card).sum
=> "#<BigDecimal:7f7cf347edd0,'0.3091675E6',18(36)>"
In my Location 'index', to be able to see a dollar amount, I have this setup as:
<%= number_to_currency(location.rate_card, :precision => 2) %>
TIA
Location.each do |e|
puts e.rate_card.to_s.to_f.round(2)
end
You're seeing :rate_card
returned as a BigDecimal because that's how it's defined in your database schema. If you were to issue Location.rate_card.class
in a Rails console you'll see => BigDecimal
.
As was mentioned by @Darby, you can use round
. In a console, issue Location.pluck(:rate_card).sum.round(2)
and that should show the desired result rounded properly.
Lastly, is there significance to the second part of your results? You show the code you're using to display the view code properly but I don't think it has bearing on your question.
A BigDecimal can be converted to a string like this.
pry(main)> b = BigDecimal.new('78.23')
=> #<BigDecimal:7ff0119cab68,'0.7823E2',18(18)>
[37] pry(main)> b.to_s
=> "0.7823E2"
You don't need to change this to a string first and then a float.
to_f
is defined on a BigDecimal object.
[34] pry(main)> b.to_f
=> 78.23
There is also to_i
and to_r
for integers and rationals respectively.