Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding a number with zeros

Tags:

string

ruby

How do I represent a number user.id as a string with:

  • 00 padded to the left if user.id is in range 0 to 9

    # => "00#{user.id}"

  • 0 padded if user.id is in range 10 to 99

    # => "0#{user.id}"

  • nothing padded otherwise

    # => "#{user.id}"

For example, having user.id = 1, it would produce "001", having user.id = 11, it would produce "011", and having user.id = 111, it would produce "111".

like image 907
Andrey Deineko Avatar asked Aug 21 '15 11:08

Andrey Deineko


People also ask

How do you pad a number with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

How do I pad zeros to a number in Excel?

In the Format Cells window, Number tab, (1) select Custom in the Category list and (2) enter 0000000000 for Type, then (3) click OK. As you can see in the Sample above Type, Excel adds as many zeros as needed until there are 10 digits.

What is a zero padded number?

Zero padding is a technique typically employed to make the size of the input sequence equal to a power of two. In zero padding, you add zeros to the end of the input sequence so that the total number of samples is equal to the next higher power of two.


1 Answers

puts 1.to_s.rjust(3, "0") #=> 001 puts 10.to_s.rjust(3, "0") #=> 010 puts 100.to_s.rjust(3, "0") #=> 100 

The above code would convert your user.id into a string, then String.rjust() method would consider its length and prefix appropriate number of zeros.

like image 115
wurde Avatar answered Sep 21 '22 20:09

wurde