Given a variable x = 12.3442
I want to know the number of decimal digits of the variable. In this case the result would be 4. How can I do this without trial and error?
Direct link to this commentnumel(erase(num2str(abs(A)),'. ')); For example, in OP's example inputting A = 12875 will output 5 for the number of digits, as desired. And A = -99.3 will output 3.
To set the format for subsequent sessions, click Preferences on the Home tab in the Environment section. Select MATLAB > Command Window, and then choose a Numeric format option. The following table summarizes the numeric output format options. Short, fixed-decimal format with 4 digits after the decimal point.
For display purposes, use sprintf to control the exact display of a number as a string. For example, to display exactly 2 decimal digits of pi (and no trailing zeros), use sprintf("%. 2f",pi) .
Here is a compact way:
y = x.*10.^(1:20)
find(y==round(y),1)
Assumes that x
is your number and 20 is the maximum number of decimal places.
As mentioned in the comments, the "number of decimal digits" does not make sense in most cases, but I think that this may be what you're looking for:
>> num = 1.23400;
>> temp = regexp(num2str(num),'\.','split')
temp =
'1' '234'
>> length(temp{2})
ans =
3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With