chris finne

Ruby Rails Initialize BigDecimal with commas in the String

22 Jul 2011

Came across a bug in the app while helping out on SpotMe.

When you create a BigDecimal, it takes a String as the argument (not a Float or Fixnum)

BigDecimal.new('99')
BigDecimal.new('44.23')

In SpotMe when someone was entering an amount for a bill or a payment, the amount might have a comma in it. The problem is that BigDecimal ignores everything to the right of the first comma it encounters

>> BigDecimal.new('1,200') == BigDecimal.new('1200')
=> false

>> BigDecimal.new('1,200') == BigDecimal.new('1')
=> true

Monkey Patch to the rescue!

>> BigDecimal.new('1,200') == BigDecimal.new('1200')
=> true

>> BigDecimal.new('1,200') == BigDecimal.new('1')
=> false

While this concept can work for just Ruby, I used Rails’ alias_method_chain. I’ve read some arguments against this approach, but in the Startup world, I’m often just trying to get the job done fast, so I like to use it.