1

I am translating some code from VB to C# and came across this:

Format(seg.R, " 00.00000;-00.00000") // <-- There is a leading space in the first format string

...which prints...

 00.00000 //or...
-00.00000

...depending on whether the decimal is positive or negative. Is there an easy way to do this with the C# string.Format or myObj.ToString("[format here]") functions?


EDIT: Notice the extra space in the format string. This makes the strings the same length by adding a leading space when there is no negative sign.

Mike Webb
  • 8,855
  • 18
  • 78
  • 111

2 Answers2

2

Yes:

http://blog.stevex.net/string-formatting-in-csharp/

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

Here's a quick answer for what you posted above:

whateverstring.ToString(" 00.00000;-00.00000");
-29.69 -> "-29.69000"
48 -> " 48.00000" <-notice space padding the front.

The semi colon separated formatting string: "00.00;##.##" applies the 00.00 pattern to Positive and zero values, and the ##.## pattern to negative values.

In other words, what you had before for a formatting string works without any tweaking :-)

Caladain
  • 4,801
  • 22
  • 24
  • Wow. The exact same format string. Figured it'd be harder than that. Couldn't find any documentation for that format either. Thanks. Worked great. – Mike Webb Dec 21 '10 at 19:03
0

Yes, String.Format() will do anything VB Classic's Format function would do.

http://blogs.msdn.com/b/kathykam/archive/2006/03/29/564426.aspx

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466