Search code examples
rubydecimalnumber-formattingpretty-print

How to pretty-print decimal format


Is there a way to change the default format of decimals when I pretty-print them?

irb(main):521:0> pp 10.to_d / 2.5   
0.4e1

I would like to format it as:

irb(main):521:0> pp 10.to_d / 2.5   
4.0

I don't really care about potential precision loss. The default format is especially annoying to read when you're pretty-printing Rails records:

<
  ...  
  id: 49391,  
  operator_id: 1,  
  tax_rate: 0.10e2,  
  sales_price: 0.1e2,  
  unit_price: 0.2e1,  
  >

I know that I can do to_s or to_f, etc., but the whole point of pretty-print is that I don't have to convert my records before I can have a quick glance at them.


Solution

  • You could monkey-patch the method the pretty-printer uses. "Normal" IRb uses inspect, but most of the pretty-printer libraries have their own methods.

    For example, the pp library from the standard library uses a method called pretty_print. BigDecimal doesn't have its own implementation of pretty_print unfortunately, it simply inherits the one from Numeric which just delegates to inspect.

    So, we can write our own!

    class BigDecimal
      def pretty_print(pp)
        pp.text to_s('F')
      end
    end
    
    pp 10.to_d / 2.5
    # 4.0