round to 2 decimal places but still have more than 2 decimal places when storing

13 ビュー (過去 30 日間)
Khairul Nur
Khairul Nur 2022 年 5 月 19 日
コメント済み: Voss 2022 年 5 月 24 日
hi,
i tried to round to 2 decimal places using (number*100)/100.However, when i used my function to store the result, the stored value not storing 2 decimal places.
There is any way, to fix this function push_ result to store 2 demical number.
%in main
new_index_table=array2table(result);
push_result(new_index_table,15);
%in function
function[]= push_result(data_to_be_pushed,tugasan)
if tugasan == 15
data_to_be_pushed_arr=table2array(data_to_be_pushed);
data_to_be_pushed_res=((round(data_to_be_pushed_arr,2))*100)/100
data_to_be_pushed_table=array2table(data_to_be_pushed_res);
if isempty(data_to_be_pushed_table); return; end
display(data_to_be_pushed_table)
filename = 'directory..NIT.dat';
[fid, message] = fopen(filename,'a');
if fid < 0
error('failed to open file "%s" because: "%s"', filename, message);
end
fmt = [repmat('%.18g ', 1, size(data_to_be_pushed_table,2)-1), '%.18g\n'];
fprintf(fid, fmt, data_to_be_pushed_table{:,:}.');
fclose(fid);
end
end

採用された回答

Voss
Voss 2022 年 5 月 20 日
"the stored value not storing 2 decimal places."
If you mean the value written to file has more than 2 decimal places, that's because you're specifying to write 18 decimal places:
fprintf('%.18g',1.23)
1.22999999999999998
If you want 2 decimal places in the file, you can use an appropriate format for that:
fprintf('%.2f',1.23)
1.23
Then you don't even have to round anything:
fprintf('%.2f',1.23123214)
1.23
  2 件のコメント
Khairul Nur
Khairul Nur 2022 年 5 月 24 日
for now..i triedd and its workk..tqqq
Voss
Voss 2022 年 5 月 24 日
You're welcome!

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2022 年 5 月 20 日
2 and 100 are relatively prime, so it is not possible for any finite base 2 fractional representation to exactly represent 1/100. This is the same reason that in decimal, no finite number of decimal places can exactly represent 1/3.
Therefore if you want to be able to round to two decimal places and have the results be exact, you will need to change representation away from binary floating point. For example you could switch to using the Symbolic Toolbox, and so be able to store exact numbers such as 373/100

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by