How to format floating point value with fix number of digits?

前端 未结 3 1996
借酒劲吻你
借酒劲吻你 2021-01-29 06:41

Is it possible in C# to format a double value with double.ToString in a way that I have always a fixed number of digits, no matter on which side of the decimal point?

Sa

3条回答
  •  无人及你
    2021-01-29 07:14

    I think some of your examples are wrong. But I still think that I understand what you want to achieve.

    I made an extension method.

    public static class StringExtensionMethods
    {
        public static string ToString(this double d, int numberOfDigits)
        {
            var result = "";
    
            // Split the number.
            // Delimiter can vary depending on locale, should consider this and not use "."
            string[] split = d.ToString().Split(new string[] { "." }, StringSplitOptions.None);
            if(split[0].Count() >= numberOfDigits)
            {
                result = split[0].Substring(0, numberOfDigits);
            }
            else
            {
                result = split[0];
                result += ".";
                result += split[1];
    
                // Add padding.
                while(result.Count() < numberOfDigits +1)
                    result += "0";
    
                result = result.Substring(0, numberOfDigits + 1);
            }
    
            return result;
        }
    }
    

    I ran it with your examples:

            double d0 = 0.00123456789;
            double d1 = 1.23456789;
            double d2 = 123.456789;
            double d3 = 0.0000000123456789;
            double d4 = 12345678.9;
            double d5 = 4.2;
    
            Console.WriteLine(d0.ToString(6));
            Console.WriteLine(d1.ToString(6));
            Console.WriteLine(d2.ToString(6));
            Console.WriteLine(d3.ToString(6));
            Console.WriteLine(d4.ToString(6));
            Console.WriteLine(d5.ToString(6));
    

    This is the output:

    0.00123 1.23456 123.456 1.23456 123456 4.20000

    I don't think this is the best way to solve it, but I like extension methods.

    DoubleConverter class: http://1drv.ms/1yEbvL4

提交回复
热议问题