Counting number of digits after the decimal points

72 visualizaciones (últimos 30 días)
Basim Touqan
Basim Touqan el 7 de En. de 2022
Editada: karipuff el 15 de Oct. de 2022
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)

Respuesta aceptada

Walter Roberson
Walter Roberson el 7 de En. de 2022
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.)

Más respuestas (3)

Matt J
Matt J el 7 de En. de 2022
Editada: Matt J el 7 de En. de 2022
If the input is numeric,
num=1.26500;
s= char( extractAfter( string(num),'.') )
s = '265'
length(s)
ans = 3

Matt J
Matt J el 7 de En. de 2022
Editada: Matt J el 7 de En. de 2022
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 el 15 de Oct. de 2022
Editada: karipuff el 15 de Oct. de 2022
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

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by