String.Format decimal with sign, fixed number of decimal places, no decimal separator
-
17-06-2021 - |
Question
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"
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)
OTHER TIPS
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.