# matlab计算结果小数点后两位,matlab保留小数点后两位.

format long

a = input('please give a number which will be changed£º');

n = input('how many decimal digits will you keep:');

num = floor(a);

str = num2str(num);

len = length(str);

err = a-num; % 获取小数部分

digits(n+len); % 此处为需要的小数位 + 整数位数

need_num = num+vpa(err,n+len); %%%% 获得按要求保留的小数,但获得的是符号性

need_str = num2str(double(need_num)) %%%%% 符号型转浮点型,再转字符型

please give a number which will be changed：3.1415926

how many decimal digits will you keep:2

need_str =

3.14

format long

a = input('please give a number which will be changed：');

n = input('how many decimal digits will you keep:');

b = a*10^n;

aa = round(b);

need_num = aa/10^n; %%%%% 先化成整数,再转成小数

need_str = num2str(need_num)

please give a number which will be changed：pi

how many decimal digits will you keep:2

need_str =

3.14

format long

a = input('please give a number which will be changed：');

n = input('how many decimal digits will you keep:');

num = floor(a);

str = num2str(num);

len = length(str);

str1 = num2str(a);

need_str = str1(1:(len+n+1)) %%%取需要的长度,这里需要加上整数长和小数点1位

please give a number which will be changed：pi

how many decimal digits will you keep:2

need_str =

3.14

a = input('please give a number which will be changed：');

n = input('how many decimal digits will you keep:');

fprintf('a = %3.2f\n',a) %%%%3.2f中.2就是小数位数

please give a number which will be changed：pi

how many decimal digits will you keep:2

a = 3.14

04-22 1039
01-30

04-19 6489
12-18 136
08-17 4441
04-22 3万+
01-04 4354
01-07 5252
01-22 8万+

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助