Make sure int variable is 2 digits long, else add 0 in front to make it 2 digits long


Question

How do I check a int variable ($inputNo) to see if it’s 2 or more decimal digits long?

Example:

inputNo="5"

Should be changed to: 05

inputNo="102"

Should be left alone: 102

I thought about using wc and if statements, but wc -m doesn’t seems to give the actual characters passed into wc, as wc always seems to give +1 to the characters that is given.

But I don’t know how to add a 0 in front of the current input number.

1
16
12/16/2009 1:48:37 PM

Accepted Answer

You can use the bash-builtin printf with the -v option to write it to a variable rather than print it to standard output:

pax> inputNo=5   ; printf -v inputNo "%02d" $inputNo ; echo $inputNo
05
pax> inputNo=102 ; printf -v inputNo "%02d" $inputNo ; echo $inputNo
102

You'll want to make sure it's numeric first otherwise the conversion will fail. If you want to be able to pad any string out to two or more characters, you can also use:

while [[ ${#inputNo} -lt 2 ]] ; do
    inputNo="0${inputNo}"
done

which is basically a while loop that prefixes your string with "0" until the length is greater than or equal to two.

Note that this can also be done in bash by prefixing the number with two zeroes then simply getting the last two characters of that string, checking first that it's not already at least the desired size:

if [[ ${#inputNo} -lt 2 ]] ; then
    inputNo="00${inputNo}"
    inputNo="${inputNo: -2}"
fi

The difference is probably not too great for a two-digit number but you may find the latter solution is better if you need larger widths.


If you're using a shell other than bash (unlikely, based on your tags), you'll need to find the equivalents, or revert to using external processes to do the work, something like:

while [[ $(echo -n ${inputNo} | wc -c) -lt 2 ]] ; do
    inputNo="0${inputNo}"
done

This does basically what you were thinking off in your question but note the use of -n in the echo command to prevent the trailing newline (which was almost certainly causing your off-by-one error).

But, as stated, this is a fall-back position. If you're using bash, the earlier suggestions of mine are probably best.

33
11/4/2015 12:59:03 AM

For general-purpose padding whether the string is numeric or not

No need for piping echo into wc or using a while loop.

In Bash, you can get the length of a string like this: ${#inputNo}.

And since you can do substrings, you can do this instead:

if [[ ${#input} < 2 ]] 
then
    inputNo="00${inputNo}"
    inputNo="${inputNo: -2}"
fi

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon