How to get the last two digits of a number?
조회 수: 60 (최근 30일)
이전 댓글 표시
Hello,
I have a table with 505 rows and 1 column. Each row contains a 4 digit number and from of these numbers I would like to extract the last two digits to add a second column to that table containing the last two digits of every number in the first column.
I would be grateful for any hints. Thank you
댓글 수: 0
채택된 답변
David Fletcher
2021년 5월 10일
x=4974
y=floor((x/100-floor(x/100))*100)
댓글 수: 3
Felician Putz
2022년 1월 22일
Be careful with floor. This can give the wrong result for some numbers. Counter example: 1001, whose result is 0 for me because apparently floor(1.0000) is 0 for Matlab.
Image Analyst
2022년 1월 22일
floor(1.0000)
x = 1001;
v = floor((x/100-floor(x/100))*100)
fprintf('%.32f', (x/100-floor(x/100))*100) % This is not 1
추가 답변 (1개)
DGM
2021년 5월 10일
Assuming they're integers:
% 10 rows random integers
n = (randi(8999,1,10)+1000)'
n = [n mod(n,100)]
If they aren't integers, you should decide how you want to round them first.
댓글 수: 3
Adam Danz
2021년 5월 10일
Either of the two existing solutions will work with 4-digit integers but note that if the 3rd digit is a 0 as in 4206, the extraction will be 6 and not 06 since matlab does not preserve the 0 place holder. If you want to retain the 0, you'll need to extract the digis as strings or character vectors.
Method 1: convert to string after extraction
rng(123) % for reprodicibility
x = round(rand(10,1)*10000);
lastTwo = mod(x,100);
charVec = compose('%02d',lastTwo); % for char-vectors
str = string(compose('%02d',mod(x,100))); % for string array
T = table(x, lastTwo, charVec, str)
Method 2: convert to string and then extract
rng(123) % for reprodicibility
x = round(rand(10,1)*10000);
xstr = string(x);
str = extractAfter(xstr,2);
T = table(x, lastTwo, str)
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!