MATLAB: Need help with leading zeroes being eaten in the function

function help leading zeroes zero sorting

I have a function that re arranges digits of a number and then subtracts them, but if the number is a single digit, I want it to include the leading zero with it. Example: say I plugged in the number 09. My function should take 09, turn it into 90, then subtract 09. Instead, it does not see the zero and does 9-9 = 0.

Best Answer

This is a bit awkward, but maybe you can improve it:
n = 9;
str2num(regexprep(fliplr(sprintf('%2d',n)),' ','0'))
This does the following:
  • The sprintf command creates a length-two string (with space if necessary for the missing digit)
  • fliplr() flips it
  • regexprep replaces the space (if there is one) with a zero
  • str2num converts it to a number