I am adding two values together and it is rounding up but I don't need it to round up.

2 ビュー (過去 30 日間)
material_cost = total * 3.67;
shipping_cost = total * 0.73;
total_cost = material_cost + shipping_cost;
fprintf('The material cost is $%0.2f. \n', material_cost);
fprintf('The shipping cost is $%0.2f. \n', shipping_cost);
fprintf('The total cost is $%0.2f. \n', total_cost);
so it prints out:
The material cost is $19.76.
The shipping cost is $3.93.
The total cost is $23.70.
the values are actually 19.7641, 3.9313, 23.6954 in the workspace.
How do I stop it from rounding the hidden numbers?

採用された回答

Image Analyst
Image Analyst 2022 年 2 月 16 日
Use more decimal places of precision if you want. Instead of 2 with $%0.2f you can use 6 with $%0.6f.
  5 件のコメント
Image Analyst
Image Analyst 2022 年 2 月 16 日
OK, great, but could you click the "Accept this answer" link? Thanks in advance. 🙂
DGM
DGM 2022 年 2 月 16 日
Since it's not really clear which behavior you want, note that the behavior of floor() and fix() differ and may matter if you process negative inputs.

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

その他の回答 (1 件)

DGM
DGM 2022 年 2 月 16 日
編集済み: DGM 2022 年 2 月 16 日
If you simply want to truncate the values to integer cents, consider the example:
A = [19.7641, 3.9313, 23.6954]
A = 1×3
19.7641 3.9313 23.6954
B = truncatecents(A)
B = 1×3
19.7600 3.9300 23.6900
fprintf('before truncation: %.2f\n',A(3))
before truncation: 23.70
fprintf('after truncation: %.2f\n',B(3))
after truncation: 23.69
function out = truncatecents(in)
out = fix(in*100)/100; % truncate toward zero
end

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by