【问题标题】:How do I format a number with custom leading characters?如何使用自定义前导字符格式化数字?
【发布时间】:2018-02-07 19:34:56
【问题描述】:

我需要用某些前导字符格式化数字。理想情况下,代码将是显而易见的,以便可以轻松维护。比如你有一个数字,比如整数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.

这个问题是在我重构一些难看的 Regex 代码时提出的,我想让其他人更容易修改和维护。

【问题讨论】:

  • 数字42怎么变成1,234.56
  • @Rufus 谢谢——为了清楚起见,我会进行编辑。

标签: c# string-formatting


【解决方案1】:

您可能对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();
}

输出

【讨论】:

  • 不错的字符串扩展;这将减轻对格式化语法的任何混淆。
【解决方案2】:

以下字符串格式应该易于理解和维护。对n 前导空格使用{0,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(s);
s = string.Format("{0}{1,8}", c, n)
    .Replace(' ', '.');          // Change leading space to period.
Console.WriteLine(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(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(s);

输出:

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

【讨论】:

  • 仅供参考,所有Console.WriteLine("{0}", s); 行都可以简化为Console.WriteLine(s);
猜你喜欢
  • 2014-07-09
  • 1970-01-01
  • 2019-12-20
  • 1970-01-01
  • 1970-01-01
  • 2014-04-27
  • 2013-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多