How can one find the last two digits of a decimal number using MATLAB
?
Example:
59 for 1.23000659
35 for 56368.35
12 for 548695412
There will always be issues when you have a decimal number with many integer digits and fractional digits. In this case, the number of integer and decimal digits decide if we are correct or not in estimating the last two digits. Let's take at the code and the comments thereafter.
Code
%// num is the input decimal number
t1 = num2str(num,'%1.15e') %// Convert number to exponential notation
t1 = t1(1:strfind(t1,'e')-1)
lastind = find(t1-'0',1,'last')
out = str2num(t1(lastind-1:lastind)) %// desired output
Results and Conclusions
For num = 1.23000659, it prints the output as 59, which is correct thanks to the fact that the number of integer and decimal digits don't add upto more than 16.
For num = 56368.35, we get output as 35, which is correct again and the reason is the same as before.
For num = 548695412, we are getting the correct output of 12 because of the same good reason.
For an out of the question sample of num = 2736232.3927327329236576 (deliberately chosen a number with many integer and fractional digits), the code run gives output as 33 which is wrong and the reason could be inferred from the fact that integer and decimal digits add upto a much bigger number than the code could handle.
One can look into MATLAB command vpa
for getting more precision, if extreme cases like the 4th one are to dealt with.
The other two answers are nice and straight forward, but here you have a mathematical way of doing it ;)
Assuming a
as your number,
ashift=0.01*a; %shift the last two digits
afloor=floor(ashift); %crop the last two digits
LastDecimals=a-100*afloor; %substract the cropped number form the original, only the last two digits left.
Of course if you have non-natural numbers, you can figure those out too with the same "floor and subtract technique as above.