Formatting a double to a string of a specific length

  • Thread starter Thread starter Pete Hodgson
  • Start date Start date
P

Pete Hodgson

I'm writing some c# code to output some data in a format that a
Fortran program can use. Yep, I said Fortran :|

What I need is to write a floating point number into a string that is
always 7 characters long, with a space prefixed before the number. For
example:

1.34567
1234.67
.234567

I figured that this would be a simple job with String.Format(), like
so:

double dNumber;
String.Format(" {0,7:g}", dNumber );

however, the output of this is something like:
91.3481478886182
141.785454332755

it seems that the alignment part of the format string is being
ignored.

Can anyone tell me what I'm missing here?
 
Pete,
I'm not sure exactly how to fix the problem, but the format is
performing as specified. In the specifications (Composite Formatting in the
help files) it says that the alignment argument is ignored if the value of
alignment is less than the width of the string. I'd try {0,7:######.######}
as the specifier which has up to 6 digits before or after the decimal. You
may have to write a custom formatter to do the as you want it.
 
I managed to find a solution. Just in case anyone else experiences a
similar problem, I solved this by changing the format string to

String.Format(" {0,7:G6}", dNumber );
 
Ah, well that explains why it was ignoring the alignment section. Thanks
for clearing that up.

I did try something similar to {0,7:######.######}, but you still get
strings longer than 7, for example 1234.5678. As I just posted, I did
managed to figure this one out anyways. Thanks for the suggestions though.
 
Ah, well that explains why it was ignoring the alignment section. Thanks
for clearing that up.

I did try something similar to {0,7:######.######}, but you still get
strings longer than 7, for example 1234.5678. As I just posted, I did
managed to figure this one out anyways. Thanks for the suggestions
though Ron.
 
Back
Top