3

What is the cleanest, most readable way to String.Format a decimal with the following criteria

  • start with a sign symbol (+ or -)
  • a fixed number of fraction digits
  • no decimal separator
  • right aligned
  • pre-padded with "0"'s

For example

  • 123,45 would become "+0012345"
  • -1123,45 would become "-0112345"
Boris Callens
  • 90,659
  • 85
  • 207
  • 305

2 Answers2

6

You almost certainly want a Custom numeric format string to pass to the String.Format method.

The custom format string can contain 2 sections (first for positive, second for negative formatting) for which you can supply the literal + or -. So to format with 7 characters zero padded this is something like:

String.Format("{0:'+'0000000;'-'0000000}",yourValue);

However, this will truncate a decimal, and so your input gives

123.45 --> +0000123
-1123.45 --> -0001123

One simple solution is just multiply your number by 100 (to fix the number of decimal digits to 2) before passing it to the above

Live example: http://rextester.com/SZR8690 (C# - sorry, but only demo's the idea)

This could then be wrapped up into an extension method:

<Extension()> 
Public Function ToFixedFormat(ByVal value As Decimal, ByVal numFractionalDigits As Integer)
    Return String.Format("{0:'+'0000000;'-'0000000}",value * Math.Pow(10,numFractionalDigits))
End Function

Live example: http://rextester.com/LSAAA60214 (VB.NET)

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • Don't worry, I'm fluent in C# too ;) Multiplying: simple and brilliant :) – Boris Callens Jun 26 '12 at 11:07
  • @BorisCallens - I thought C# would be ok, but we should always strive to provide code examples in the tagged language of choice. The fixed number of digits was the only part `String.Format` cant do (not without a decimal separator anyway) So your 2 choices are replace the decimal place (as per @Tim's answer) or multiply by the nth power of 10 (as per my answer). – Jamiec Jun 26 '12 at 11:15
3

Maybe there's something better because it looks a bit clumsy, but it works.

I specify the positive and negative format to enforce the plus-sign for positive numbers and a fixed size string. Then i use the InvariantCulture to enforce the point as decimal separator (i could have used other cultures too). The last step is to remove the point.

Dim value = -1123.45
Dim formatted = value.ToString(
        "+00000.00;-00000.00",
        System.Globalization.CultureInfo.InvariantCulture)
formatted = formatted.Replace(".", "")

As you can see i don't know how to specify no decimal separator.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939