Format double type with minimum number of decimal digits

后端 未结 3 1379
猫巷女王i
猫巷女王i 2021-01-04 03:11

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          


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-04 03:40

    Try this

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

提交回复
热议问题