- 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
Need help with leading zeroes being eaten in my function
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.
0 件のコメント
採用された回答
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:
1 件のコメント
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
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!