0

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

Alan
  • 459
  • 6
  • 20

2 Answers2

1

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) %>
Jagdeep Singh
  • 4,880
  • 2
  • 17
  • 22
0

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])
spickermann
  • 100,941
  • 9
  • 101
  • 131