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
Advertisements

About sandipransing

Web Developer #ruby #rails #JS
This entry was posted in Ruby. Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s