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"
.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With