Note that there are some explanatory texts on larger screens.

plurals
  1. PORails - Format number as currency format in the Getter
    primarykey
    data
    text
    <p>I am making a simple retail commerce solution, where there are <strong>prices</strong> in a few different models. These prices contribute to a <strong>total price</strong>. Imagine paying $0.30 more for selecting a topping for your yogurt. </p> <p>When I set the <code>price</code> field to </p> <pre><code>t.decimal :price, precision:8, scale:2 </code></pre> <p>The database stores <code>6.50</code> as <code>6.5</code>. I know in the standard rails way, you call <code>number_to_currency(price)</code> to get the formatted value in the Views. I need to programmatically call the <code>price</code> field as well formatted string, i.e. $6.50 a few places that are not directly part of the View. Also, my needs are simple (no currency conversion etc), I prefer to have the price formatted universally in the model without repeated calling number_to_currency in views.</p> <p>Is there a good way I can modify my getter for price such that it always returns two decimal place with a dollar sign, i.e. $6.50 when it's called? </p> <p>Thanks in advance.</p> <p><strong>UPDATE</strong></p> <p>Thanks everyone.</p> <p>I've elected to use Alex's approach because it seems very 'hackish' to do the includes just for formatting the number. Using his approach, I did:</p> <pre><code> def price_change=(val) write_attribute :price_change, val.to_s.gsub(/[\$]/,'').to_d end def price_change "$%.2f" % self[:price_change] end </code></pre> <p>Cheers. </p> <p><strong>UPDATE 2</strong></p> <p>Caveat Emptor. Once you do this, you lose the ability to do operations to the number because it's now a string. </p> <p>Please beware if anyone is facing the same problem as me.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload