Saturday, April 13, 2013

Localize Currency and I18N String Interpolation

number_to_currency is new to Rails 3.2.13

I found it necessary to specify the currency format options for each locale, which I put in separate .yml files, but you can put all of them in one .yml file for testing.

Open the rails console and include the NumberHelper class

>> include ActionView::Helpers::NumberHelper
=> Object

>> number_to_currency(1234567890.506)
=> "$1,234,567,890.51"

>> number_to_currency(1234567890.506, :locale => :en)
=> "$1,234,567,890.51"

>> number_to_currency(1234567890.506, :locale => :en_gb)
=> "1,234,567,890.51 £"

>> number_to_currency(1234567890.506, :locale => :fr)
=> "1 234 567 890.51 €"

>> number_to_currency(1234567890.506, :locale => :br)
=> "R$  1.234.567.890,51"

Locale yml File(s)


en:
  hello: "Hello world"
  hello-you: "Hello %{name}!"
  inbox:
    counting:
      one: You have 1 new message
      other: You have %{count} new messages
      zero: You have no messages  
  greetings:
    hello: "Hello"
    hey: "Hey"
  number:
    currency:
        format:
          significant: !'false'



fr:
  hello-you: "bonjour %{name}!"
  number:
    currency:
      format:
        format: "%n %u"
        unit: "€"
        delimiter: " "
        

en_gb:
  number:
    currency:
      format:
        format: "%n %u"
        unit: "£"

br:
  number:
    currency:
      format:
        format: "%u %n"
        unit: "R$ "
        delimiter: "."
        separator: ","


String Interpolation

You can build your I18N strings dynamically, assuming your .yml locale file is setup properly.

>> I18n.t("hello-you", {name: "John Doe"})
=> "Hello John Doe!"

>> I18n.t("inbox.counting", {count: 10})
=> "You have 10 new messages"

>> I18n.t(["greetings", "hello"])
=> [{:hello=>"Hello", :hey=>"Hey"}, "Hello world"]

>> I18n.t("hello-you", {locale: :fr, name: "John Doe"})
=> "bonjour John Doe!"

References

http://webdesign.about.com/od/localization/l/blhtmlcodes-cur.htm
https://github.com/fnando/i18n-js
https://github.com/jquery/globalize


Sponsor Ads(Say "Thanks!" by clicking the Ad below)

1 comment: