how to calculate the number of digits after decimal point?
6 次查看(过去 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
0 个评论
采纳的回答
Greig
2015-8-30
Try something like this
a = 1.6556;
splt = regexp(num2str(a), '\.', 'split');
dps = str2num(splt{2})
1 个评论
Walter Roberson
2015-8-30
This is not actually correct, though it would certainly usually look that way. See my Answer.
更多回答(1 个)
Walter Roberson
2015-8-30
编辑:Walter Roberson
2015-8-30
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 个评论
Walter Roberson
2015-8-30
I am not sure which is my "second code".
I caution again that the sprintf() version is only suitable for OS-X as MS Windows does not support extended field widths at all and Linux gets the answers wrong after some number of decimal points.
Another thing that I would point out is that if you are going after the integer representation rather than the string representation, then you are not able to distinguish between 0.123 and 0.0000123 as 123 and 0000123 have the same integer value.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!