フィルターのクリア

Need help with leading zeroes being eaten in my function

7 ビュー (過去 30 日間)
Tony
Tony 2014 年 4 月 29 日
回答済み: Tony 2014 年 4 月 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 Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by