Skip to content
Related Articles

Related Articles

Improve Article

How to remove decimal in MATLAB?

  • Last Updated : 29 Jul, 2021
Geek Week

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




% MATLAB code for removal of 
% decimal points using sprintf()
% Initializing some values
A = 3.000;
B = 1.420;
C = 0.023;
  
% Calling the sprintf() function over
% the above values
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




% MATLAB code for removal
% of decimal points with fix()
% Initializing some values
A = 3.000;
B = 1.420;
C = 0.023;
  
% Calling the fix() function over
% the above values
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




% MATLAB code for removal of 
% decimal points using floor()
% Initializing some values
A = 2.000;
B = 1.790;
C = 0.9093;
  
% Calling the floor() function over
% the above values
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




% MATLAB code for  removal of
% decimal points using round()
% Initializing some values
A = 2.300;
B = 1.790;
C = 0.9093;
D = 0.093;
  
% Calling the round() function over
% the above values
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




% MATLAB code for  removal of
% decimal points without rounding
% Initializing some values
  
num2str(3.1455567, '%.0f')

Output:

ans = 3



My Personal Notes arrow_drop_up
Recommended Articles
Page :