How to get the same number of char as number of decimals using num2str?
Ältere Kommentare anzeigen
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:
>> dec = get_decimals(3.141592653)
str =
'3.1416'
decimals =
1416
How to solve it?
Thanks in advance.
Best,
louis
Akzeptierte Antwort
Weitere Antworten (1)
James Tursa
am 16 Sep. 2022
0 Stimmen
You might look into using the fix( ) function to isolate the fractional part of your number and then work with that directly.
7 Kommentare
Louis Tomczyk
am 16 Sep. 2022
James Tursa
am 16 Sep. 2022
Bearbeitet: James Tursa
am 16 Sep. 2022
It is unclear to me whether you want truncated digits as your original post, or rounded digits as your later post. Regardless, here is what I meant by using the fix( ) function to isolate the fractional part:
f = x - fix(x)
Then you could work with f directly using num2str( ) or some other method.
@Louis Tomczyk is the purpose is to test a number is an integer (not the class is subtypes of integer) why not simply use modulo (try to avoid to convert to string that is only convenient for human but not so for computer)
isint = @(x) mod(double(x),1) == 0;
% Few examples
isint(3)
isint(-10)
isint(pi)
isint(1+eps)
Louis Tomczyk
am 16 Sep. 2022
Bearbeitet: Louis Tomczyk
am 16 Sep. 2022
James Tursa
am 16 Sep. 2022
Bearbeitet: James Tursa
am 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)
Louis Tomczyk
am 17 Sep. 2022
Kategorien
Mehr zu Logical finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!