Overriding to_s method for BigDecimal instance

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 :late_s :to_s
  def to_s
    return to_i.to_s if eql? to_i
    self.late_s
  end
end

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.