Converting a large decimal place to a string in the Rails console

I am trying to get my console to print the total cost of all my Locations tariff cards.

I am trying to complete this task through the console, but as a result I get BigDecimal. Stuck on how to convert this result to a human-readable string or integer.

Results:

Location.pluck(:rate_card).sum => "#<BigDecimal:7f7cf347edd0,'0.3091675E6',18(36)>" 

In my "index" location, to see the dollar amount, I have this setting as:

  <%= number_to_currency(location.rate_card, :precision => 2) %> 

TIA

+7
count console sum ruby-on-rails-4
source share
3 answers
 Location.each do |e| puts e.rate_card.to_s.to_f.round(2) end 
+9
source share

You see :rate_card returned as BigDecimal, since it is defined in your database schema. If you are going to release Location.rate_card.class in the Rails console, you will see => BigDecimal .

As @ Darby already mentioned, you can use round . In the console, enter Location.pluck(:rate_card).sum.round(2) and this should show the desired result, rounded correctly.

Finally, is there any significance to the second part of your results? You are showing the code that you use to correctly display the view code, but I do not think it is relevant to your question.

+3
source share

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 do not need to change this to a string first and then to a float. to_f defined in the BigDecimal object.

 [34] pry(main)> b.to_f => 78.23 

There is also to_i and to_r for integers and rationals, respectively.

+1
source share

All Articles