Hi.
That is my code.
float_number = input('Please enter a float point number: ');
fprintf("The number is %.2f\n",float_number);
Sample test:
Please enter a float point number: 5.126
The number is 5.13
When the user enters a decimal, the result only keeps two decimal places, but I don't want the last decimal place to be rounded.
I don't want 5.13. I want 5.12.
How to do it?
Thank you.

 採用された回答

the cyclist
the cyclist 2022 年 6 月 16 日
編集済み: the cyclist 2022 年 6 月 16 日

1 投票

Here is one way:
roundTo = 2; % Set this value
float_number = 5.126; % User's value
% Algorithm
roundToPower = 10^roundTo;
roundedDisp = floor(float_number*roundToPower)/roundToPower;
fprintf("The number is %.2f\n",roundedDisp);
The number is 5.12

3 件のコメント

Shuoze Xu
Shuoze Xu 2022 年 6 月 16 日
Thank you.
Dose the matlab have others way to achive that?
Because i am a new guy on matlab, I like to know more simple method.
Stephen23
Stephen23 2022 年 6 月 16 日
"I like to know more simple method."
Ultimately all numeric -> text conversion routines perform rounding, which is a good thing because it provides the most expected output from binary floating point numbers. For example:
x = 0.3
x = 0.3000
fprintf('%.40f\n',x)
0.2999999999999999888977697537484345957637
A naive "simple" approach might simply truncate this to 0.29, which is unlikely to be what the user expects.
The cyclist's approach is good, performing a few basic numeric operations is not complex.
Walter Roberson
Walter Roberson 2022 年 6 月 16 日
MATLAB does not provide any built-in function for this purpose.
For MacOS only (not sure if Linux was fixed yet), you can sprintf the number with a %.800g format, and do text manipulation on the result to get the number of decimal places you want.

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

その他の回答 (0 件)

カテゴリ

製品

リリース

R2021b

タグ

質問済み:

2022 年 6 月 16 日

編集済み:

2022 年 6 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by