如何使用自定义前导字符格式化数字?

时间:2018-02-07 19:34:57

标签: c# string-formatting

我需要一个用某些前导字符格式化的数字。理想情况下,代码将是显而易见的,以便可以轻松维护。例如,如果您有一个数字,例如42的整数或货币金额$1234.56,则输出以下格式:

FOO.....42       A customer specified ID number format with leading periods.
$ xxxxxxx42      Format for dollar amounts with leading x's.
$ ~~~~1,234.56   Format for printing checks with leading tilde.

当我重构一些丑陋的正则表达式代码时出现了这个问题,我想让其他人更容易修改和维护。

2 个答案:

答案 0 :(得分:2)

应易于理解和维护以下字符串格式。对{0,n}前导空格使用n字符串格式,然后在.Replace()之后修改字符串。

var n = 1234;
var c = "FOO";
var d = 1234.56;
var s = string.Format("{0}{1,8}", c, n); // The ",8" denotes up to 8 leading spaces.
Console.WriteLine("{0}", s);
s = string.Format("{0}{1,8}", c, n)
    .Replace(' ', '.');          // Change leading space to period.
Console.WriteLine("{0}", s);
s = string.Format("$_{0,8}", n)  // Up to 8 leading spaces.
    .Replace(' ', 'x')           // Replace spaces with 'x'.
    .Replace('_', ' ');          // Replace the leading underscore with space.
Console.WriteLine("{0}", s);
s = string.Format("$_{0,12:#,#.##}", d) // Decimal format with leading spaces.
    .Replace(' ', '~')           // Replace spaces with '~'
    .Replace('_', ' ');          // Replace the leading underscore with space.
Console.WriteLine("{0}", s);

输出:

FOO    1234
FOO....1234
$ xxxx1234
$ ~~~~1,234.56

答案 1 :(得分:2)

您可能对PadLeft方法感兴趣,该方法将任意字符串的左侧部分填充多个字符,以使整个字符串长度等于指定的长度。显然,如果字符串已经大于或等于指定的长度,它就不会做任何事情。

以下方法接受字符串,前缀和字符作为前缀和字符串之间的填充。它做了一些初始验证,将空字符串更改为空字符串,并根据所需长度检查字符串长度,然后使用PadLeft填充具有指定字符的字符串:

private static string PrefixAndPad(string text, string prefix, char padChar, int length)
{
    text = text ?? "";
    prefix = prefix ?? "";

    if (text.Length >= length) return text;
    if (prefix.Length + text.Length >= length) return prefix + text;

    return prefix + text.PadLeft(length - prefix.Length, padChar);
}

然后您就可以使用它:

private static void Main()
{
    // Our input strings, which are numbers converted to strins
    string str1 = 42.ToString();

    // The following line formats as currency ("c") then removes the currency symbol
    string str2 = 1234.56.ToString("c").Replace("$", "");

    Console.WriteLine(PrefixAndPad(str1, "FOO", '.', 10));
    Console.WriteLine(PrefixAndPad(str1, "$ ", 'x', 11));
    Console.WriteLine(PrefixAndPad(str2, "$ ", '~', 14));

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

<强>输出

enter image description here