When you want to print the number n width total with w, you can use
n=12
w=8
printf "%0*d\n" $w $n
When you want the result in a var, you can use
printf -v j "%0*d" $w $n
echo "j=[$j]"
# Result:
j=[00000012]
It becomes more complex when you want to support strings as well.
A simple patch seems to work
s="Hello"
w=8
# Wrong:
printf "%*s\n" $w "$s" | tr ' ' '0'
The problem with this solution is that it will also replace the spaces in $s. You can use a sed construction for this:
s="Hello World with Spaces"
w=40
printf "%*s\n" $w "$s"| sed -r ':a;s/^( *) /\10/;ta'
j=$(printf "%*s" $w "$s"| sed -r ':a;s/^( *) /\10/;ta')
The sedconstruction will loop over the input, replacing one space each time (the last leading space) with a 0. The \1 will put back the other leading spaces.
When it is hard to understand, look how to replace 2 spaces by 'x':
printf "%*s\n" $w "$s"| sed -r 's/^( *) /\1x/;s/^( *) /\1x/'
EDIT: The solution is not perfect. When the inputstring starts with spaces, these spaces are replaced by zeroes too, and that might not be desired behaviour: s=" I started with a space".
The solution seems to be calculating the number of zeroes first: The total width $w minus the stringlength ${#s}. When you need at least one additional 0, you can use
printf "%0*d%s\n" $(($w - ${#s})) 0 "$s"