MATLAB: Find the precision of a value

decimaldecimal digitsdigitsfloating pointfprintfprecisionsigfigssignificant figuresstring

Hello,
Is there a function in matlab that returns the precision of a number? for example, if I have a number 5.34 i want it to return 0.01, if I have a number 4 I want it to return 1 etc..
Thanks in advance for your answers,

Best Answer

No doubt there will be disagreements over what it means for floating point numbers, but here is one solution which provides the least unexpected output by converting to string, converting the last non-zero digit to 1 and the rest to 0. I do not claim that it is fast, but it does seem to be reasonably robust.
function p = getprecision(x)
f = 14-9*isa(x,'single'); % double/single = 14/5 decimal places.
s = sprintf('%.*e',f,x);
v = [f+2:-1:3,1];
s(v) = '0'+diff([0,cumsum(s(v)~='0')>0]);
p = str2double(s);
end
and tested:
>> getprecision(5.34)
ans = 0.010000
>> getprecision(5)
ans = 1
>> getprecision(53400)
ans = 100
Notes:
  1. keep in mind that 5.34 and 0.01 do not really exist in binary floating point numbers. See Adam's comment.
  2. '%g' is an obvious choice, but is actually more complicated because it can return fixed point values with trailing zeros.