Ruby print number with leading zeros

When needing to print out a number with leading 0 the easiest way I found was:

some_number = 3

result_string = "%02d" % some_number # => "03"

After the percent symbol the 2 tells ruby the minimal length of the number and the 0 tells it what to put in if the length is not met (default is a whitespace i.e. space).

Should a larger number be passed to the output format for example 1234, the output will be “1234”, so it will not be shortened.

Advertisements

One Response to Ruby print number with leading zeros

  1. Hubert says:

    Thanks!

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

%d bloggers like this: