Counting number of digits after the decimal points
조회 수: 72 (최근 30일)
이전 댓글 표시
Dear colleagues/friends
Kindly help, i need you to kindly teach me how do I count the number of digits after the decimal point of any number in MATLAB.
For exmaple i have the number 1.26500
Which matlab command or algorith i can use to count the non zero digits after the decimal point and get (3)
댓글 수: 0
채택된 답변
Walter Roberson
2022년 1월 7일
x = 1.26500
xstr = sprintf('%.999g', x)
afterdot_pos = find(xstr == '.') + 1;
if isempty(afterdot_pos); afterdot_pos = length(xstr) + 1; end
number_of_decimals = length(xstr) - afterdot_pos + 1
and get (3)
But 3 is not correct -- at least not if your value is a number.
Floating point numbers are not stored in decimal -- or at least not on any computer you are likely to have used. Binary floating point numbers won out a number of decades ago, except for some financial systems and on missile guidance systems.
Basically, unless you are using an IBM Z1 series of computers, your hardware is highly unlikely to be able to represent 1/10 exactly .
When you code 1.26500, then MATLAB does not store the exact ratio 1265 / 1000: it stores a number A/2^B that best approximates 1265 / 1000 . In the case of 1.26500 then the exact decimal representation of what is stored is 1.2649999999999999023003738329862244427204132080078125
To do better, you need to store as a rational pair yourself (and keep track of all of the appropriate factors), or you need to store as text and manipulate the text, or you need to use the Symbolic Toolbox (which does not actually store decimal either, but hides it better.)
댓글 수: 0
추가 답변 (3개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!