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”
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:However, this will truncate a decimal, and so your input gives
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:
Live example: http://rextester.com/LSAAA60214 (VB.NET)