by simon baird

Tuesday, May 11, 2010

hack to fix broken number_to_currency in ruby on rails

The rails function number_to_currency for some reason puts the negative sign after the currency symbol. So you get this kind of thing: $-123.55 instead of -$123.55.

Someone wrote a patch for this, see here, but it seems to have been forgotten. So here is my dirty hack.

I put it in module ApplicationHelper in app/helpers/application_helper.rb.

  # The number_to_currency function puts the negative sign after the dollar sign instead of before it.
  # This is a hack to fix that behaviour. Use at your own risk. It shouldn't cause harm when used with
  # other currencies, but it won't fix the negative sign unless it finds $- at the start of the string.
  def number_to_currency_fix_negative(number, options={})
    number_to_currency(number, options).sub(/^\$-/, '-$')
It could be improved obviously to work with currencies other than dollars.

And for convenience you might like to do a monkey patch version of this fix. I leave that as an exercise...

(Disclaimer: Written by a rails noob).


Anonymous said...

Thankfully, this has been fixed in Rails 3.0.2. It naturally puts the - sign in the correct place. You also have the option to specify your own format for negative currencies so that you can put the negative sign where you want or you can use parenthesis!

simon said...

cool, thanks for the info