how to calculate the number of digits after decimal point?

3 views (last 30 days)
say i have a data a=1.6556, somehow i need to use a function which gives 6556 i.e., digits after the decimal, and if a=256 then the result should be zero. please help

Accepted Answer

Greig
Greig on 30 Aug 2015
Try something like this
a = 1.6556;
splt = regexp(num2str(a), '\.', 'split');
dps = str2num(splt{2})
  1 Comment
Walter Roberson
Walter Roberson on 30 Aug 2015
This is not actually correct, though it would certainly usually look that way. See my Answer.

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 30 Aug 2015
Edited: Walter Roberson on 30 Aug 2015
If you are on MS Windows then you need to get num2strexact() from the File Exchange. Then you can
a = 1.6556;
splt = regexprep(num2strexact(a), '^[^.]*\.', '');
dps = str2double(splt);
You will find that the answer is approximately 6.556e+51 and that the exact answer, available as a string in splt, is 6555999999999999605648781653144396841526031494140625
Why is that the exact answer and not 6556 ? It is because 0.6556 cannot be represented exactly in binary floating point arithmetic, because 1/10 is an infinite repeating number in binary just as 1/7 is an infinite repeating number in decimal. The number that is actually stored for 1.6556 is 1.6555999999999999605648781653144396841526031494140625 . You do not see this because the "format" you are using is rounding off to 4 decimal places.
If you had a = 1.3733243 then the typical "format short" that is in effect would display
a =
1.3733
What value would you want as output? The 3733 that it was displayed as, or the 3733243 that it was assigned as? Probably what it was assigned as. But once it is assigned then all MATLAB knows is the internal numeric representation, in binary floating point, and the actual internal representation of 1.3733243 is 1.3733242999999999423010876853368245065212249755859375 . Those digits are "really there", just the same way that the .3733243 is "really there" even though only 1.3733 was displayed.
If you only want the answer to a certain number of decimal places, e.g., D = 5 for 5 decimal places, then use
x = abs(a); %account for negative numbers
round((x - floor(x)) * 10^D)
  6 Comments
Paromita Bhattacharjee
Paromita Bhattacharjee on 30 Aug 2015
I meant the code before the OS-X code. Thank you for all your help.

Sign in to comment.

Categories

Find more on Numeric Types in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by