How do I right pad a numeric data field with invisible characters?
조회 수: 6 (최근 30일)
이전 댓글 표시
I have a column of data values of varying units of measure. I want to embed the ValueDisplayFormat with the units. For example, 0.00 m, easily done as %.2f m. I want the numeric values to right-align, but have yet to find a means to right pad the character array. I've tried a variety of so-call invisible Unicode characters, the pad function, etc, but in every instance the actual display would strip out the spaces, whether the standard ASCII space or any of the Unicode characters.
댓글 수: 0
답변 (1개)
Star Strider
2022년 12월 15일
편집: Star Strider
2022년 12월 15일
It would help to know more precisely what you want to do.
Numeric format dexcriptors can be created as a total numeric field length with or with out leading zeros or spaces or a mandatory sign (so a plus gets printed for positive values as would a minus for negative values). The sign and decimal point would need to be included in the total size of the numeric filed descirptor.
x = pi^2;
simple = sprintf('%.2f m',x)
left_padded = sprintf('%10.2f m',x) % 10 Characters Total = 1 Sign Position + One Decimal Position + Two Digits To The Right Of the Decimal = 6 Possible Figures To The Left Of The Decimal
I’m not certain what you want, however it is relatively straightforward to ‘left-pad’ a number.
EDIT — To shift them to the left (left-justify) the numeric field, precede the numeric descriptor with a negative sign —
left_justified = sprintf('%-10.2f m',x)
.
댓글 수: 2
Walter Roberson
2022년 12월 15일
Notes:
- If you use a leading 0 in the field will be left-padded with 0 if needed to reach the requested width. For example, '%010.2f
- The field width such as the 10 in %10.2f is the minimum field width for the total representation of the value including sign and decimal and exponent. If more character positions are needed then more will be used. For example a %10.2f format is not wide enough for 2e+50
- remember to include space for the negative sign if the value might be negative
- then '-' flag requests left justification within the field and leading 0 are supressed in that case
- remember if you are using a proportional font then spaces are going to be a different width (assuming rendering to display rather than file), so unless you are using 0 fill and have no negative values, you should be sure to use a monospace font.
sprintf('%010.2f', -3.9), length(ans)
sprintf('%010.2f', 2e50), length(ans)
sprintf('%-010.2f', -3.9), length(ans)
sprintf('%-10.2f', .39), length(ans)
참고 항목
카테고리
Help Center 및 File Exchange에서 NaNs에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!