格式双固定宽度 C#

Format Double to fixed Width C#

我的要求如下:

我有双号。它可以是积极的,也可以是消极的。我想用 String.Format() 来格式化它。

输出数字(正数(无符号)/负数(含符号)/零)应固定宽度:11 所有数字都应保留 2 位小数。

示例:

1.2     00000001.20
.2      00000000.20
-.2     -0000000.20
12      00000012.00
0       00000000.00
-0      00000000.00
12.555  00000012.55

基本上,我想要的是定宽(11位)。 2 小数点。没有积极的迹象。固定宽度中包含负号。

我尝试过的:

{0:00000000.00;0:0000000.00;0:00000000.00}

请告诉我正确的方法是什么。

string.Format("{0:00000000.00}", 1.2) 

对我来说很好

double d = -12.365;
string s = d.ToString("0:00000000.00");   //-0:00000012.37
string sOut = d.ToString("00000000.00");  //-00000012.37

您可以使用部分修饰符来提供您需要的输出:

string format = "{0:00000000.00;-0000000.00}";

Console.WriteLine(string.Format(format, 1.2));
Console.WriteLine(string.Format(format, .2));
Console.WriteLine(string.Format(format, -.2));
Console.WriteLine(string.Format(format, 12.0));
Console.WriteLine(string.Format(format, -0.0));
Console.WriteLine(string.Format(format, 12.555));

打印出来:

00000001.20
00000000.20
-0000000.20
00000012.00
00000000.00
00000012.56

基本上是{position:postive format;negative format;zero format}

注意:position只用于格式化字符串,你也可以在没有"position"元素的情况下与double.ToString(string)一起使用; 如果未提供零格式,则使用正格式部分的格式来格式化零。

有关 ; 部分格式的更多详细信息,请参阅 https://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx

负数需要第二个格式部分。如果您需要重用它,将其声明为 Func 或扩展方法可能会有所帮助。像这样:

using System;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<double, string> toFixedWidth = (d) => { 
                return string.Format("{0:00000000.00;-0000000.00}", d); 
            };

            foreach (var d in new double[] { 1.2, 0.2, -0.2, 12, 0, -0, 12.555 })
            {
                Console.WriteLine(toFixedWidth(d));
            }
        }
    }
}

00000001,20
00000000,20
-0000000,20
00000012,00
00000000,00
00000000,00
00000012,56
Press any key to continue . . .

这是一个通用函数。它的工作原理与其他答案相同,但它会根据 length (总长度)和 decimals 参数动态构建格式字符串。

public static string FormatDoubleAsFixedLengthString(double value, int length, int decimals)
{
    int wholeDigits = length - decimals;

    // Provide a spot for the negative sign if present.
    if (value < 0)
    {
        wholeDigits--;
    }

    string wholeDigitsFormat = new String('0', wholeDigits);
    string decimalDigitsFormat = new String('0', decimals);
    string format = $"{{0:{wholeDigitsFormat}.{decimalDigitsFormat}}}";
    return string.Format(format, value);
}

虽然我们在这里,但这里有相同的函数,但用于 整数 :

public static string FormatIntAsFixedLengthString(int value, int length)
{
    // Provide a spot for the negative sign if present.
    if (value < 0)
    {
        length--;
    }
    return string.Format($"{{0:D{length}}}", value);
}