【问题标题】:ToString format for fixed length of output - mixture of decimal and integer固定长度输出的 ToString 格式 - 小数和整数的混合
【发布时间】:2022-11-10 20:41:37
【问题描述】:

我正在编写一些代码来显示报告的数字。数字的范围可以从 1. 到数千,所以我需要显示的精度取决于值。

我希望能够在.ToString() 中传递一些东西,这将给我至少 3 位数字——整数部分和小数部分的混合。

前任:

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

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

【问题讨论】:

  • 怎么样:ToString("G3")
  • @PoulBak - 我不想显示指数。整个计划是这个数字已经划分好了,比如显示125万,或者1.23亿。
  • 好吧,一旦你划分了数字,那么ToString("G3") 应该可以工作 - 至少在你给出的例子中。你试过了吗?
  • @PoulBak G3 可以解决一半的问题。对于任何可能的数字,他至少需要 3 位数字,并且末尾没有 E+

标签: c# tostring


【解决方案1】:

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

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.

【讨论】:

    【解决方案2】:

    我认为这不能单独使用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;
    }
    

    【讨论】:

      【解决方案3】:

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

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

      解释

      ^ 从字符串的开头匹配

      任何一个

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

      或者

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

      或者

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

      首先划分您的号码,然后在正则表达式之前调用ToString()

      【讨论】:

      • “[^.]+ 不超过一个点的任意位数”这是不正确的。从技术上讲,它将返回所需的匹配只要它适用于有效号码但我会更明确地使用d+ 而不是[^.]+
      • 此外,当您传递“2”时,它将返回“2”,而 OP 在这种情况下想要“2.00”(即“至少三位”)。
      • @41686d6564:你从一个数字开始,所以它会起作用。我还将“至少三位”读为:“19232.12 -> 19232”。但这当然取决于 OP。
      【解决方案4】:

      实现这个的简单方法就是写 ToString("f2") 两个十进制数只需更改此 fnumber 即可获得所需的十进制值数和整数值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-03
        • 2019-06-02
        • 1970-01-01
        • 1970-01-01
        • 2017-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多