How to format both left and right of the decimal place with sprintf?

28 ビュー (過去 30 日間)
Darrian Low
Darrian Low 2025 年 12 月 7 日 10:39
コメント済み: Walter Roberson 2025 年 12 月 7 日 18:43
I have four numbers below:
  1. 964.155
  2. 9590.43
  3. 350.76
  4. 0.00
These numbers need to be re-formatted to the following:
  1. 0964.16 (rounded up from .155)
  2. 9590.43
  3. 0350.76
  4. 0000.00
I have tried using the following code but to but to no avail.
sprintf('%4.2f, the_number)
What do I need to change in my code?

採用された回答

Walter Roberson
Walter Roberson 2025 年 12 月 7 日 11:33
N = [964.155
9590.43
350.76
0.00];
fprintf('%07.2f\n', N)
0964.15 9590.43 0350.76 0000.00

その他の回答 (1 件)

Dyuman Joshi
Dyuman Joshi 2025 年 12 月 7 日 11:42
編集済み: Dyuman Joshi 2025 年 12 月 7 日 11:44
Here's an approach -
y = [964.155
9590.43
350.76
0.00];
You'll have to manually round up, as sprintf() doesn't do that (See this thread - https://in.mathworks.com/matlabcentral/answers/24638-round-towards-even-in-sprintf)
z = sprintf('%07.2f\n', round(y, 2))
z =
'0964.16 9590.43 0350.76 0000.00 '
As you want a total of 7 characters to be displayed (4 before the decimal, 1 - the decimal itself and 2 after the decimal), if there aren't sufficient total characters, pad them with zero - Thus the '07' in the call.

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by