Search code examples
rubystringnumber-formatting

Put + sign in front of positive numbers in ruby


I like to display a plus sign before positive numbers. Example

2.to_s
# returns +2

and

-2.to_s
# returns -2

Solution

  • Use Kernel#sprintf with a + flag:

    sprintf('%d', 11)
    # 11
    sprintf('%+d', 11)
    # +11
    

    or equivalently, String#%:

    '%+d<x>' % { x: 23 }
    # +23