My code
<td><%= number_to_currency(x['quote']['USD']['price'], :unit => '$', :separator =>'.', :delimiter => ',', precision: 4) %><br/></td>
When I use it just like that, it is ok, extract the info and put it ok. But when I try to multiply with another variable, it send me an error "ActiveSupport::SafeBuffer can't be coerced into BigDecimal", so I was thinking in turn it into a #, but I am not sure how to do it
You could think number_to_currency returns a special string (e.g. "$ 123.0000"), it can't be multiplied with number directly.
You could multiply first, then use number_to_currency to format result:
<% result = x['quote']['USD']['price'] * crypto.cost_per %>
<td><%= number_to_currency(result, unit: '$', separator: '.', delimiter: ',', precision: 4) %></td>
Related
I have a rails app which deals with product prices from different countries.
Storing GBP, and USD is working fine. However, when I start to deal with the CLP (Chilian peso) which has 3 decimal places, it's not storing right.
For example, I am trying to insert 799.990 but when it goes in its storing as 799.99. It is not ideal as there could be a price of 799.99.
I have the price set to t.decimal :price, precision: 19, scale: 4 so this should cover most currencies.
So, my question is there any way to store the price with the trailing 0? Or am I missing something, is there a better way to deal with currencies in rails?
Update:
After searching a bit more on StackOverflow, I think this may be an easier way of dealing with currencies.
number_to_currency locale converting
As 799.99 is same as 799.990 in terms of the amount, you don't need to modify the database column to store the trailing "0". You can simply edit your view to display 3 digits after decimal:
<% if #product.currency == 'CLP' %>
Price: <%= '%.3f' % #product.price %>
<% else %>
<!-- Existing logic -->
<% end %>
Update
Another option is to use sprintf:
<%= sprintf('%.3f', #product.price) %>
As Jagdeep already wrote in his answer, you only need to format the number when you render it to a page.
I would use Rails' number_to_currency helper for this:
CURRENCY_OPTIONS = {
'CLP' => { unit: '$', precision: 3 },
'EUR' => { unit: '€', precision: 2 },
'USD' => { unit: '$', precision: 2 }
}
number_to_currency(price, CURRENCY_OPTIONS[currency])
I spent most part of today trying to figure out how to give my integer fields a currency format and was bombarded with a myriad of different approaches from using Money, Rails-Money gems to using custom helper methods or locales.
You can achieve this by using the number_to_currency method. Say you
have the following view:
view.html.erb
<ul>
<li><%= client.payment %></li>
</ul>
Assuming the column payments is of type integer, this will print out just that, a number with no formatting. Ex: 5523
Now add the number_to_currency method and specify which currency unit
you'd like to use (can be any)
<ul>
<li><%= number_to_currency(client.payment, :unit => "$") %></li>
</ul>
Now we get something like this: 5.523.00$
The number_to_currency method helper has some options by default, one
of those is that it inverts (as opposed to common practice) the usage
of comma and period. These can be modified by adding the options
:separator and :delimiter and give them the values you'd like as is
below.
<ul>
<li><%= number_to_currency(client.payment, :unit => "$", :separator => ".", :delimiter => ",") %></li>
</ul>
These are the available options for the number_to_currency method helper (RubyOnRailsAPI):
:locale - Sets the locale to be used for formatting (defaults to current locale).
:precision - Sets the level of precision (defaults to 2).
:unit - Sets the denomination of the currency (defaults to “$”).
:separator - Sets the separator between the units (defaults to “.”).
:delimiter - Sets the thousands delimiter (defaults to “,”).
:format - Sets the format for non-negative numbers (defaults to “%u%n”). Fields are %u for the currency, and %n for the number.
:negative_format - Sets the format for negative numbers (defaults to prepending a hyphen to the formatted number given by :format). Accepts the same fields than :format, except %n is here the absolute value of the number.
:raise - If true, raises InvalidNumberError when the argument is invalid.
You can do it a few different ways. Personally I would recommend doing this in a decorator (https://github.com/drapergem/draper) to remove some logic and formatting out of the view.
As mentioned in a prior answer you can use number_to_currency and not use other options to get the correct formatting you are looking for. It can take an integer, float, or string.
number_to_currency 10000
=> "$10,000.00"
Another way is to use money-rails (https://github.com/RubyMoney/money-rails) if you want to deal with a Money object:
money = Money.new(10000)
=> #<Money fractional:10000 currency:USD>
humanized_money_with_symbol money
=> "$10,000.00"
Have you tried using it without any options?
number_to_currency(client.payment)
It should default to $ and has worked fine for me without any options.
I'm using Rails and wanted to convert a float to currency. I'm using number_to_currency in a Sidekiq Worker, so I've added include ActionView::Helpers::NumberHelper in the file and where I want the conversion I've added the following:
number_to_currency(value, unit: '', delimeter: '.', separator: ',')
And I wanted the result something like: 1.200,09 but its not working. An example of values I have and want to convert is: 1001.4290000000004 which should be converted to 1.001,43. I've also tried:
number_to_currency(final_total, unit: '', delimeter: ',', separator: '.')
And still doesn't work. I'm getting is 1,200.09. I'm using Rails 4.2.x
What am I missing here?
If you want get result like this 1001.4290000000004 => 1,001.43, you can use this method:
number_with_delimiter(value , delimiter: ",", separator: ".")
But befor u need convert value to the desired value:
value = 1001.4290000000004.round(2) #=> 1001.43
You just have a typo in word delimiter. It should be as follows:
number_to_currency(value, unit: '', delimiter: '.', separator: ',')
I'm creating a Rails 3.1 app and I've the following big issue: I must retrieve some parameter from view to controller
This is my view:
<tr class="<%= cycle("odd", "even") %>">
<td><%= text_field_tag("bulk_warehouse_serial#{#count}_page#{params[:page]}", bulk_warehouse.serial, :disabled => true) %></td>
<td><%= text_field_tag("bulk_warehouse_asset#{#count}_page#{params[:page]}", bulk_warehouse.asset, :disabled => true)%></td>
<td><%= check_box_tag "enable_record#{#count}_page#{params[:page]}",1,false,{:onclick => "bulk_warehouse_serial#{#count}.disabled =
bulk_warehouse_asset#{#count}.disabled =
!this.checked;"}%></td>
<td class="last">
<%= link_to "#{t("web-app-theme.delete", :default => "Delete")}", bulk_warehouse_path(bulk_warehouse), :method => :delete, :confirm => "#{t("web-app-theme.confirm", :default => "Are you sure?")}" %>
</td>
</tr>
</div>
<% #count = #count +1 %>
And in my controller I've something such as:
...
#count = 0
...
and this what is generated by web server log:
"warehouse"=>{"asset"=>"turiturira", "serial"=>"caricarira", "project_id"=>"1", "hardware"=>{"brand_id"=>"21"}, "hardware_id"=>"60", "state_id"=>"4", "position_id"=>"1", "logicalwarehouse_id"=>"3", "extra_id"=>"3"}, "bulk_warehouse_serial270"=>"t", "bulk_warehouse_asset270"=>"test", "enable_record2_page0"=>"1", "bulk_warehouse_serial2"=>"uela2", "bulk_warehouse_asset2"=>"bela2", "enable_record3_page0"=>"1"}_
e
Now, in my controller I need an action where I must check first all "enable_record#{#count}_page#{params[:page]}" values and then doing some actions. How can I make if statement in my controller? I was thinking something such as:
#count=0
#page = params[:page]
#count_max = 10
until #count == #count_max
if params[:warehouse][:enable_record#{#count}_page#{params[:page]}] == 1
...doing something...
end
#count=#count+1
end
but it gives me an surror; any suggestions?
This seems quite complicated for whatever it is you're trying to do, but I'll refrain from refactoring your approach. There is one standout in your code however -- it is the dynamic construction of the key you're using. You may want to construct it with a string then 'symbolize' it:
key = "enable_record#{#count}_page#{params[:page]}".to_sym
if params[:warehouse][key] == 1
...doing something...
end
Note: you also might reconsider the equality condition. The hash's value may not be an integer 1 as your code suggests and could actually be "1" (a string). Ensure both values are the same type (using either .to_s or .to_i) if there's any uncertainty.
I need to format float like price for two decimal places and thousands spaces, like this:
"1 082 233.00"
Use number_to_currency or number_with_precision:
number_with_precision(1082233, :precision => 2,
:separator => '.',
:delimiter => ' ')
# => '1 082 233.00'
See the NumberHelper documentation for details.