grabbing number after decimal
271 views (last 30 days)
More Answers (5)
Image Analyst on 20 Aug 2014
neesha, what if there are 3 or 4 numbers after the decimal point? Do you want only the first one, or all of them? What if you did
fractions = t.specialNumber - floor(t.specialNumber);
where t is the table and specialNumber is the column in the table. So for example 73.8234 would give 0.8234 as a result. Would that work for you? Or do you only want the 8 as 8 and not as 0.8 or 0.8234?
Hikaru on 20 Aug 2014
Edited: Hikaru on 20 Aug 2014
One way to do this
specialNumber = [1234.5; 9087.3];
d = abs(specialNumber - fix(specialNumber));
answer = d*10; %assuming that your data only has one decimal place
final = round(answer)
Note: This is not really the best solution since subtracting floating points can introduce error.
Patrik Ek on 20 Aug 2014
Since there have been a discussion about floating point errors here (which IMO seems to be overkill to care about for this operation) I will provide an integer casting solution. This should be free from floating point issues since no addition or subtraction is done with floating points.
N = 1234.537;
nDigits = 2;
R = cast(floor(10^nDigits*N),'int32') - cast(10^nDigits*floor(N),'int32');
R = cast(R,'double') % If double is important then cast it back
The floor in the first term is there because of matlabs solution of casting, which rounds the double to closest int.