#ruby

Padding numbers with zeros in Ruby

February 29, 2020

//

30 sec read

String#% method allows to specify format to apply to its argument. It can be used to pad numbers with zeros.

Leading zeros

> "%03d" % 2
=> "002"

Trailing zeros

> "%.2f" % 2
=> "2.00"