C# - 字符串格式:双固定宽度

时间:2012-09-28 15:09:01

标签: c# double fixed-width custom-formatting

如何在C#中使用String.Format,因此双打显示如下:

值:

-1.0
1.011
100.155
1000.25
11000.52221

显示字符串:

-1.00
1.011
100.2
 1000
11001

重点是我的宽度固定为5个字符,无论如何。我真的不在乎右边显示了多少小数位。如果十进制左边有4个或更多数字,我希望删除小数点的所有内容(包括小数本身)。

这似乎应该是一种非常标准的做法。但我找不到一个有效的答案我没有太多运气。

对上面的显示字符串进行了几处更正,我确实想要四舍五入。

谢谢!

3 个答案:

答案 0 :(得分:3)

通常这条规则适用于外汇市场,我将其发展如下:

if (number < 1)
   cell.Value = number.ToString("0.00000");
else if (number < 10)
   cell.Value = number.ToString("0.0000");
else if (number < 100)
   cell.Value = number.ToString("00.000");
else if (number < 1000)
   cell.Value = number.ToString("000.00");
else if (number < 10000)
   cell.Value = number.ToString("0000.0");
else if (number < 100000)
   cell.Value = number.ToString("00000");

答案 1 :(得分:2)

public string FormatNumber(double number)
{
    string stringRepresentation = number.ToString();

    if (stringRepresentation.Length > 5)
        stringRepresentation = stringRepresentation.Substring(0, 5);

    if (stringRepresentation.Length == 5 && stringRepresentation.EndsWith("."))
        stringRepresentation = stringRepresentation.Substring(0, 4);

    return stringRepresentation.PadLeft(5);
}

编辑:刚才意识到如果必要的话,这不会在小数结尾处填充零(如第一个示例中所示),但应该为您提供工具以根据需要完成它。

EDITx2:鉴于您最近想要进行四舍五入的添加,它会变得更复杂。首先,您必须检查 if ,您将获得任何小数位以及小数位于何处。然后你必须将它四舍五入到小数位,然后可能会运行输出。请注意,根据您的算法,您可能会在舍入滚动数字时得到一些不正确的结果(例如,-10.9999可能会变为-11.00-11,具体取决于您的实施方式)

答案 2 :(得分:1)

如果要经常在很多地方使用,请在Double上创建一个扩展方法。

using System;

public static class DoubleExtensionMethods
{
    public static string FormattedTo5(this double number)
    {
        string numberAsText = number.ToString();

        if (numberAsText.Length > 5)
        {
            numberAsText = numberAsText.Substring(0, 5);
        }

        return numberAsText.TrimEnd('.').PadLeft(5);
    }
}

用法将是:

double myDouble = 12345.6789D;

string formattedValue = myDouble.FormattedTo5();