格式为double类型,最小小数位数

Sib*_*Guy 14 .net c#

我需要格式化double类型,使其至少有两位小数,但不限制最大小数位数:

5     -> "5.00"
5.5   -> "5.50"
5.55  -> "5.55"
5.555 -> "5.555"
5.5555 -> "5.5555"
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现它?

Guf*_*ffa 37

您可以使用0特定格式的非可选数字和#可选数字:

n.ToString("0.00###")
Run Code Online (Sandbox Code Playgroud)

此示例为您提供最多五位小数,您可以#根据需要添加更多位置.


San*_*G B 3

尝试这个

    static void Main(string[] args)
    {
        Console.WriteLine(FormatDecimal(1.678M));
        Console.WriteLine(FormatDecimal(1.6M));
        Console.ReadLine();

    }

    private static string FormatDecimal(decimal input)
    {
        return Math.Abs(input - decimal.Parse(string.Format("{0:0.00}", input))) > 0 ?
            input.ToString() :
            string.Format("{0:0.00}", input);
    }
Run Code Online (Sandbox Code Playgroud)