rounding string to certain decimal places

15 ビュー (過去 30 日間)
I W
I W 2020 年 11 月 10 日
編集済み: I W 2021 年 12 月 17 日
%This command generates a random number. %Do not overwrite the value of number in your own code. number = 10*rand(1,1); %Enter the commands for your script mfile here. formatSpec = "The number rounded to two decimal places is %d."; A1 = round(number, 2) rounded_to_2 = sprintf(formatSpec,A1) formatSpec = "The number rounded to four decimal places is %d."; A1 = round(number, 4) rounded_to_4 = sprintf(formatSpec,A1) but the rounded value is not what I want. For example I want the value to be 5.34 but it displays 5.340000e+00

採用された回答

Steven Lord
Steven Lord 2020 年 11 月 10 日
When you include %d in your format specifier for sprintf you're telling sprintf that it should expect an integer value in that position. Your values, rounded to two decimal places, may not be integer values. Look at the description of the format specifier input on the documentation page for sprintf (doc sprintf) and see if there's an entry that looks more suitable for floating-point data that may not be integer values.

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by