Counting number of digits after the decimal points
76 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Basim Touqan
el 7 de En. 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)
0 comentarios
Respuesta aceptada
Walter Roberson
el 7 de En. de 2022
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 comentarios
Más respuestas (3)
Ver también
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!