PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

[FIXED] How to pretty-print decimal format

 October 24, 2022     decimal, number-formatting, pretty-print, ruby     No comments   

Issue

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


Answered By - Jörg W Mittag
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing