-
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.
x = three point one four one five nine ; fprintf( '%.2f\n' , x); %The output result is 3.14
-
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.
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