Read more

Helpers to render (money) amounts

Henning Koch
June 16, 2011Software engineer at makandra GmbH

When rendering a number, you want to pretty up the string coming from #to_s:

  • Render 0.0 as 0
  • Sometimes require a minimum number of digits after the decimal separator
  • Change the decimal separator from . to , in some European countries
  • Render a dash if the given amount is nil
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

The attached helper that does just that. Some usage examples with their resulting strings:

Invocation Result
amount(0) 0
amount(0.0) 0
amount(0.5) 0,5
amount(1.5, :minimum_precision => 2) 1,50
amount(1.543, :minimum_precision => 2) 1,543
amount(1.5, :minimum_precision => 2, :separator => '.') 1.50
amount(nil)

Rendering money amounts

If your amounts are Western hemisphere money amounts, you want some additional prettifications on top of that:

  • Always use a minimum precision of 2
  • Render a currency symbol after the string

A second helper method in the attached file does just that. Some usage examples with their resulting strings:

Invocation Result
money_amount(0) 0,00 €
money_amount(0.0) 0,00 €
money_amount(0.5) 0,50 €
money_amount(1.543) 1,543 €
money_amount(0.5, :unit => '₣') 0,50 ₣
money_amount(nil)
Henning Koch
June 16, 2011Software engineer at makandra GmbH
Posted by Henning Koch to makandra dev (2011-06-16 11:30)