固定长度输出的 ToString 格式 - 小数和整数的混合

ToString format for fixed length of output - mixture of decimal and integer

我正在编写一些代码来显示报告的数字。数字可以从 1 到几千不等,因此我需要显示的精度取决于值。

我希望能够在 .ToString() 中传递至少 3 位数字 - 整数部分和小数部分的混合。

例如:

1.2345 -> "1.23"
21.552 -> "21.5"
19232.12 -> "19232"

使用 000 作为格式不起作用,因为它不显示任何小数,0.000 也不显示 - 当整个部分大于 10 时显示太多小数。

我认为仅靠 ToString() 是做不到的。

相反,首先用 2 个尾随数字格式化数字,然后根据需要截断:

static string FormatNumber3Digits(double n)
{
    // format number with two trailing decimals
    var numberString = n.ToString("0.00");

    if(numberString.Length > 5)
        // if resulting string is longer than 5 chars it means we have 3 or more digits occur before the decimal separator
        numberString = numberString.Remove(numberString.Length - 3);
    else if(numberString.Length == 5)
        // if it's exactly 5 we just need to cut off the last digit to get NN.N
        numberString = numberString.Remove(numberString.Length - 1);

    return numberString;
}

你可以为此写一个扩展方法:

public static string ToCustomString(this double d, int minDigits = 3)
{
    // Get the number of digits of the integer part of the number.
    int intDigits = (int)Math.Floor(Math.Log10(d) + 1);
    // Calculate the decimal places to be used.
    int decimalPlaces = Math.Max(0, minDigits - intDigits);
    
    return d.ToString($"0.{new string('0', decimalPlaces)}");
}

用法:

Console.WriteLine(1.2345.ToCustomString());    // 1.23
Console.WriteLine(21.552.ToCustomString());    // 21.6
Console.WriteLine(19232.12.ToCustomString());  // 19232

Console.WriteLine(1.2345.ToCustomString(minDigits:4));    // 1.235

Try it online.

这是一个正则表达式,它将为您提供任意数字的三位数字(如果没有小数点,则所有数字都匹配):

@"^(?:\d\.\d{1,2}|\d{2}\.\d|[^.]+)"

解释:

^ 从字符串开头开始匹配

任一

\d\.\d{1,2} 一个数字后跟一个点后跟 1 或 2 个数字

\d{2}\.\d 2 位数字后跟一个点和 1 位数字

[^.]+ 不超过一个点的任意数字。

先除你的号码,然后在正则表达式前调用ToString()