String formatting does not behave as expected when using padding
I am trying to form a text representation of a table based off of the result coming in from a SqlDataReader.
while (unitsRdr.Read())
{
note.AppendFormat("{0,-15}", String.Format("{0}({1})", unitsRdr.GetValue(0), unitsRdr.GetValue(1)));
}
Now what I expect to happen is I should get 4 sets of items, that will have padding on the right hand side equal to 15. Like this
BP(mm\Hg) HR(bpm) RR(rpm) Sa O2(%) |<-- this would be th开发者_Python百科e end of the string.
However what I am getting is
BP(mm\Hg )HR(bpm )RR(rpm )Sa O2(% )|<-- this is the end of the string.
It appears to start counting after the (
and the )
is put after the number of spaces.
What is the correct way of doing formatting so the text is like my first example?
For anyone who wants it here is the source table
desc unit
------------ ----------
BP mm\Hg
HR bpm
RR rpm
Sa O2 %
I strongly suspect that the problem is that the value returned by unitsRdr.GetValue(1)
is actually longer than you believe. I very much doubt that string.Format
is doing that. Try using unitsRdr.GetValue(1).Trim()
instead - or just test it with a hard-coded literal value.
精彩评论