Friday, October 22, 2010

Overriding to_s method for BigDecimal instance

by Sandip Ransing 0 comments

requirement was to display decimal numbers which are having scale values present to be displayed in decimal format otherwise display them as integer.

Output expected
12.23 => 12.23
12.00 => 12


While rendering any object on html page by default "to_s" method gets executed. So, i overwrote "to_s" method of BigDecimal class as below.

Anyone having better solution. Please reply with your solutions. Many thanks!
Put below code in file "config/intializers/core_extensions.rb"

class BigDecimal alias :old_s :to_s def to_s return to_i.to_s if eql? to_i self.old_s end end

blog comments powered by Disqus

About The Author

Sandip is a ruby on rails developer based in pune and also a blogger at funonrails. Opensource contributor and working with Josh software Private Limited. for more info read Follow Sandip on Twitter for updates.

Connect With Me...

Github Projects

@sandipransing Twitter