Search code examples
ruby-on-railsformattingbigdecimal

Rails formatting BigDecimal


My question it's simple (I think):

In Rails I have custom datetime format function called l, there are a equivalent for BigDecimal?

Example that I want:

index.html.erb

<%= l bill.date, format: :od %>
<%= ? bill.total_amount, format: :o2d %>
<%= ? bill.tax_amount, format: :o2d %>

I want to represent BigDecimal as currency with money symbol, but now I use:

<%= number_to_currency bill.total_amount, unit: '&euro;', separator: ',', delimiter: '.', format: '%n %u' %>

It's seems dirty?

Thanks in advance.


Solution

  • This ruby gem will help you.

    https://github.com/RubyMoney/money

    Probably you have to implement your own view helper, and you should implement in it as like follows.

    money = Money.new(1000, "USD")
    money.cents => 1000
    money.symbol => $    
    
    def money_helper(money)
      "#{money.symbol}#{money.cents}" 
    end
    
    <%= money_helper 1000 %> => $1000
    

    More Configs:

    curr = {
      :priority        => 1,
      :iso_code        => "USD",
      :iso_numeric     => "840",
      :name            => "United States Dollar",
      :symbol          => "$",
      :subunit         => "Cent",
      :subunit_to_unit => 100,
      :separator       => ".",
      :delimiter       => ","
    }
    
    
    The pre-defined set of attributes includes:
    
    :priority a numerical value you can use to sort/group the currency list
    :iso_code the international 3-letter code as defined by the ISO 4217 standard
    :iso_numeric the international 3-digit code as defined by the ISO 4217 standard
    :name the currency name
    :symbol the currency symbol (UTF-8 encoded)
    :subunit the name of the fractional monetary unit
    :subunit_to_unit the proportion between the unit and the subunit
    :separator character between the whole and fraction amounts
    :delimiter character between each thousands place