双格式与类型的小数位数最小数小数、位数、类型、格式

2023-09-03 15:56:54 作者:╰苍穹盛夏、仰望那丝余光

我需要格式化double型,使其具有最小的小数点后两位数,但不限于小数最大位数:

I need to format double type so that it has minimum two decimal digits but without limitation for maximum number of decimal digits:

5     -> "5.00"
5.5   -> "5.50"
5.55  -> "5.55"
5.555 -> "5.555"
5.5555 -> "5.5555"

我怎样才能实现呢?

How can I achieve it?

推荐答案

试试这个

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