How to get the same number of char as number of decimals using num2str?
9 views (last 30 days)
Show older comments
Louis Tomczyk
on 16 Sep 2022
Commented: Louis Tomczyk
on 17 Sep 2022
Dear all,
I want to get the decimal part of a number.
I have written this small function:
function dec = get_decimals(input)
str = num2str(input) % convert to string
index = strfind(str,'.'); % locate the comma/point
dec = str2double(str(index+1:end)); % take the end
end
However if my input has too many decimals, the
function will truncate my number:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1127345/image.png)
>> dec = get_decimals(3.141592653)
str =
'3.1416'
decimals =
1416
How to solve it?
Thanks in advance.
Best,
louis
0 Comments
Accepted Answer
More Answers (1)
James Tursa
on 16 Sep 2022
You might look into using the fix( ) function to isolate the fractional part of your number and then work with that directly.
7 Comments
James Tursa
on 16 Sep 2022
Edited: James Tursa
on 16 Sep 2022
@Louis Tomczyk As you have just learned, it is best to post your real problem up front so as to avoid answers that don't really help you. In addition to Bruno's latest comment, here are other methods for determining if a finite number is an integer value:
x==fix(x)
x==floor(x)
x==round(x)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!