Need help with leading zeroes being eaten in my function

6 次查看(过去 30 天)
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.

采纳的回答

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

请先登录,再进行评论。

更多回答(2 个)

dpb
dpb 2014-4-29
编辑:dpb 2014-4-29
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 2014-4-30
Thanks guys, give me a few days to work with these methods and I will get back to you soon.

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by