1

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
Divakar
  • 218,885
  • 19
  • 262
  • 358
bzak
  • 563
  • 1
  • 8
  • 21

3 Answers3

1

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

  1. 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.

  2. For num = 56368.35, we get output as 35, which is correct again and the reason is the same as before.

  3. For num = 548695412, we are getting the correct output of 12 because of the same good reason.

  4. 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.

Divakar
  • 218,885
  • 19
  • 262
  • 358
0

Convert to string and then extract the last two characters:

x = 1.23;           % x = 1.23
s = num2str(x);     % s = "1.23"
t = s(end-1:end);   % t = "23"
u = str2num(t);     % u = 23

Note: depending on your specific needs you might want to supply a precision or formatSpec to num2str.

Paul R
  • 208,748
  • 37
  • 389
  • 560
0

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.

McMa
  • 1,568
  • 7
  • 22