Variable number of left zeros in Matlab string

106 Views Asked by At

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?

2

There are 2 best solutions below

0
Shai On BEST ANSWER

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

num2str( 122, '%04d' );

or

sprintf( '%04d', 32 );
2
Tony Hopkinson On

This will left pad up to 4 0s

sprintf('%04d', some_value);