String.Format decimal with sign, fixed number of decimal places, no decimal separator

.net, decimal, string.format, vb.net

Solution

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)

Problem

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"

Original source