How do I right pad a numeric data field with invisible characters?
4 次查看(过去 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)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!