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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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