Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to add zeros to front of a number string using sprintf()

Tags:

string

ruby

I want to normalize zipcodes to be 5 digits long with zeros replacing any missing characters like so:

"95616" >> "95616"
"854"  >> "00854"
"062" >> "00062"
"0016" >> "00016"

I have tried using sprintf like so sprintf("%05s", zipcode) and like so sprintf("%0.5d", zipcode). Both give incorrect answers. Using the s:

"95616" >> "95616"
"854"   >> "  854"
"062"   >> "  062"
"0016"  >> " 0016"

This is the correct number of characters, but using spaces, not zeros.

Using the d:

"95616" >> "95616"
"854"   >> "00854"
"062"   >> "00050"
"0016"  >> "00014"

What is the proper use of sprintf() in this case?

like image 882
VictorO Avatar asked Dec 28 '12 23:12

VictorO


People also ask

How do you add a leading zero to a string?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.

How do you add leading zeros to a string in C #?

If you want a leading zero in front of that, use "0%c". But again, "%c" is just a character, not a decimal integer or anything like that. For example, if you tried to print "0%c" to a string with the character 65, you would get the string "0A" (but by passing a size of 2 to snprintf, the string would always be "0").


1 Answers

Don't torture yourself with sprintf:

puts "123".rjust(5, '0') # => 00123
like image 161
steenslag Avatar answered Sep 23 '22 23:09

steenslag