Counting number of digits after the decimal points

62 ビュー (過去 30 日間)
Basim Touqan
Basim Touqan 2022 年 1 月 7 日
編集済み: NgoiKH 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

NgoiKH
NgoiKH 2022 年 10 月 15 日
編集済み: NgoiKH 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 Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by