Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find number of decimal digits of a variable in MATLAB

Tags:

matlab

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?

like image 326
PVaz Avatar asked May 13 '13 17:05

PVaz


People also ask

How do I count the number of digits in MATLAB?

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.

How do I show 4 decimal places in MATLAB?

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.

How do I control the number of decimal places in MATLAB?

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) .


2 Answers

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.

like image 191
Dennis Jaheruddin Avatar answered Oct 04 '22 02:10

Dennis Jaheruddin


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
like image 20
Roney Michael Avatar answered Oct 04 '22 02:10

Roney Michael