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?
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.
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").
Don't torture yourself with sprintf
:
puts "123".rjust(5, '0') # => 00123
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