-->

C# - 字符串格式:双固定宽度(C# - String formatting: double fi

2019-09-23 04:03发布

我怎样才能使用String.Format在C#这样的双打显示是这样的:

价值观:

-1.0
1.011
100.155
1000.25
11000.52221

显示字符串:

-1.00
1.011
100.2
 1000
11001

主要的一点是我的宽度无论什么固定的5个字符。 我真的不关心有多少小数位如右图所示。 如果存在4个或多个数字到小数点左边我想要的一切权利小数被丢弃(包括小数点本身)。

看来喜欢的事,应该是一个非常标准的做法。 但我没有多少运气找到问题的解答。

一对夫妇更正的是,以显示字符串做出以上,我确实想四舍五入。

谢谢!

Answer 1:

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:鉴于你最近除了你打算有舍入,它变得更加复杂。 首先,你必须做一个检查,看看你是否有任何小数和在什么位置小数点是。 然后,你必须把它四舍五入至小数点后一位,那么很可能通过输出运行。 请注意,这取决于你的算法,你可以得到其中的舍入对数字辊的一些不正确的结果(例如, -10.9999可能成为-11.00-11取决于你的实现)



Answer 2:

通常这个规则应用于外汇市场上,我开发它,如下:

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");


Answer 3:

创建于如果双它要经常使用,在许多地方的扩展方法。

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();


文章来源: C# - String formatting: double fixed width