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

5 views (last 30 days)
Khairul Nur
Khairul Nur on 19 May 2022
Commented: Voss on 24 May 2022
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

Accepted Answer

Voss
Voss on 20 May 2022
"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

More Answers (1)

Walter Roberson
Walter Roberson on 20 May 2022
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

Community Treasure Hunt

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

Start Hunting!