Cheap VPS host selection
Provide server host evaluation information

How to change the decimal digits of output value in matlab

In MATLAB, you can use the following methods to change the number of decimal places of the output value:

  1. use fprintf Function: fprintf The function is used to format the output. You can control the number of decimal places of the output by specifying the format string. For example, you can use fprintf('%.2f', x) Change the variable x The value of is output with two decimal places.

Sample code:

 x = three point one four one five nine ; fprintf( '%.2f\n' , x); %The output result is 3.14
  1. Use string arrays and string Function: You can convert a number to a string, and then use the string array operation method to control the number of decimal places disp or fprintf Function output.

Sample code:

 x = three point one four one five nine ; str = string(x); %Convert a number to a string str = extractBefore(str, '.' ) + extractAfter(str, '.' , two ); %Extract the digits before and after the decimal point (keep two decimal places)
 disp (str); %The output result is 3.14

It should be noted that the above method only affects the display format of output, and does not change the actual value. If you need to round a variable or calculate to retain a specific number of decimal places, use the relevant function (for example round fix Etc.).

Do not reprint without permission: Cheap VPS evaluation » How to change the decimal digits of output value in matlab