MATLAB Answers

how to calculate the number of digits after decimal point?

61 ビュー (過去 30 日間)
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


Greig 2015 年 8 月 30 日
Try something like this
a = 1.6556;
splt = regexp(num2str(a), '\.', 'split');
dps = str2num(splt{2})
  1 件のコメント
Walter Roberson
Walter Roberson 2015 年 8 月 30 日
This is not actually correct, though it would certainly usually look that way. See my Answer.


その他の回答 (1 件)

Walter Roberson
Walter Roberson 2015 年 8 月 30 日
編集済み: Walter Roberson 2015 年 8 月 30 日
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 =
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 件のコメント
Paromita Bhattacharjee
Paromita Bhattacharjee 2015 年 8 月 30 日
I meant the code before the OS-X code. Thank you for all your help.



Community Treasure Hunt

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

Start Hunting!

Translated by