Adding 0 to beginning of a number

Hi

Is there a quick way to add 0 to the beginning of a number if it only
has one digit?

ie
1 should be 01
11 should stay as 11

(These int’s can be transferred to a string)

Thanks

On Tue, 2006-07-04 at 18:19 +0200, ben wrote:

Hi

Is there a quick way to add 0 to the beginning of a number if it only
has one digit?

ie
1 should be 01
11 should stay as 11

(These int’s can be transferred to a string)


have to be converted to a string to work…

if my_var < 10
my_var = “0” + my_var.to_s
else
my_var = my_var.to_s
end

Craig

ben wrote:

Thanks

If you need to “convert” them only for output, you should be able to use
printf/ sprintf or format… just use “%02d” as the format specifier for
the number.

Cheers
Mohit.

sprintf “%02d”, my_var

or:

format “%02d”, my_var

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs