How to remove decimal in MATLAB?
In this article, we are going to discuss the “Removal of decimal point” in MATLAB which can be done using sprintf(), fix(), floor(), round() and num2str() functions which are illustrated below.
Using sprintf()
The sprintf() function is used to write formatted data to a string.
Syntax:
sprintf(format, A)
Here, sprintf(format, A) is used to format the data in A over the specified format string.
Example:
Matlab
A = 3.000;
B = 1.420;
C = 0.023;
sprintf( '%.f' , A)
sprintf( '%.f' , B)
sprintf( '%.f' , C)
|
Output:
ans = 3
ans = 1
ans = 0
Using fix()
The fix() function is used to round the specified values towards zero.
Syntax:
fix(A)
Here, fix(A) is used to round the specified elements of A toward zero which results in an array of integers.
Example:
Matlab
A = 3.000;
B = 1.420;
C = 0.023;
fix(A)
fix(B)
fix(C)
|
Output:
ans = 3
ans = 1
ans = 0
Using floor()
The floor() function is used to round the specified values towards minus infinity.
Syntax:
floor(A)
Here, floor(A) function is used to round the specified elements of A to the nearest integers less than or equal to A.
Example:
Matlab
A = 2.000;
B = 1.790;
C = 0.9093;
floor(A)
floor(B)
floor(C)
|
Output:
ans = 2
ans = 1
ans = 0
Using round()
The round() function is used to round the specified values to their nearest integer.
Syntax:
round(X)
Here, round(X) function is used to round the specified elements of X to their nearest integers.
Example1:
Matlab
A = 2.300;
B = 1.790;
C = 0.9093;
D = 0.093;
round(A)
round(B)
round(C)
round(D)
|
Output:
ans = 2
ans = 2
ans = 1
ans = 0
Now we see how to remove decimal places without rounding. For this, we can use num2str, which converts numbers to a character array.
Using num2str( )
The num2str() function is used to convert the specified numbers to a character array.
Syntax: num2str(num)
Parameters: This function accepts a parameter.
- num: This is the specified number.
Example:
Matlab
num2str(3.1455567, '%.0f' )
|
Output:
ans = 3
Last Updated :
29 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...