Search code examples
matlabzero-pad

Variable number of left zeros in Matlab string


I want to do exactly what is on this question, but instead of having to give a fixed number of left-side zeros, to be able to give the fixed number of digits that the number has to have in total.

For example, if I have the number 32, and have a length of 4, the result should be:

0032

But if on contrary I have the number 122, then only one 0 should be padded:

0122

any ideas on how to achieve this on Matlab efficiently? sprintf?


Solution

  • You can use string formatting in num2str as well as in sprintf:

    num2str( 122, '%04d' );
    

    or

    sprintf( '%04d', 32 );