Counting number of digits after the decimal points

조회 수: 72 (최근 30일)
Basim Touqan
Basim Touqan 2022년 1월 7일
편집: karipuff 2022년 10월 15일
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)

채택된 답변

Walter Roberson
Walter Roberson 2022년 1월 7일
x = 1.26500
x = 1.2650
xstr = sprintf('%.999g', x)
xstr = '1.2649999999999999023003738329862244427204132080078125'
afterdot_pos = find(xstr == '.') + 1;
if isempty(afterdot_pos); afterdot_pos = length(xstr) + 1; end
number_of_decimals = length(xstr) - afterdot_pos + 1
number_of_decimals = 52
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.)

추가 답변 (3개)

Matt J
Matt J 2022년 1월 7일
편집: Matt J 2022년 1월 7일
If the input is numeric,
num=1.26500;
s= char( extractAfter( string(num),'.') )
s = '265'
length(s)
ans = 3

Matt J
Matt J 2022년 1월 7일
편집: Matt J 2022년 1월 7일
If the input is in string form,
num="1.26500"; %input
s= fliplr( char( extractAfter( num,'.') ))
s = '00562'
numel(s)- sum(find(s~='0',1))+1
ans = 3

karipuff
karipuff 2022년 10월 15일
편집: karipuff 2022년 10월 15일
function [N_decimal] = countdecimal(value)
max_round_dec = 15;
for N_decimal = 0:max_round_dec
val = rem(value,10^(-N_decimal));
if val == 0
return
end
end
end

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by