Clear Filters
Clear Filters

Need help with leading zeroes being eaten in my function

7 views (last 30 days)
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.

Accepted Answer

the cyclist
the cyclist on 29 Apr 2014
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
  1 Comment
Kelly Kearney
Kelly Kearney on 29 Apr 2014
Or to skip the regexp step, use a formatting string that pads with 0s:
a = 9;
str2num(fliplr(num2str(a, '%02d'))) - a

Sign in to comment.

More Answers (2)

dpb
dpb on 29 Apr 2014
Edited: dpb on 29 Apr 2014
If you read the value as numeric, internal storage is what it is; there are no "leading zeros". The only way you can do something like this is by keeping the string representation and reversing it before doing the numerical operations.
SOTOO--
>> in='09'
in =
09
>> res=str2num(fliplr(in))-9 % result as numeric
res =
81
>> res=num2str(str2num(fliplr(in))-9) % result as string
res =
81
>>
ADDENDUM:
NB: In your invocation, despite entering '09' it's automagically converted to internal numeric representation. You would have to either enter as a string (using the ' ' to surround the value) or use input or similar to get the input and leave it as string (the optional 's' argument).
Or, to make your current work, you could change to sotoo...
>> in=09
in =
9
>> res=str2num(fliplr(num2str(in,'%2.2d')))-9
res =
81
>>
You'll need to make the field width dynamic depending on the size of the input value and how many leading zeros you wish as that will predicate the actual value in the end.
Unfortunately, you can't count the leading zeros a user typed in if you don't save the input as string to begin with--they're not significant in parsing and so are discarded.

Tony
Tony on 30 Apr 2014
Thanks guys, give me a few days to work with these methods and I will get back to you soon.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!