Format double type with minimum number of decimal digits

后端 未结 3 1375
猫巷女王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:15

    Something like ToString("0.00#") should work

    In this case it would be max to 3 decimal places, so add hash as required.

    0 讨论(0)
  • 2021-01-04 03:35

    You can use the 0 format specificer for non-optional digits, and # for optional digits:

    n.ToString("0.00###")
    

    This example gives you up to five decimal digits, you can add more # positions as needed.

    0 讨论(0)
  • 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);
        }
    
    0 讨论(0)
提交回复
热议问题