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

前端 未结 3 1998
借酒劲吻你
借酒劲吻你 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:03

    As I understand, there is no predefined format that does what I need. So for everyone who is interested, here is the function I ended up with:

    public string FormatValue(double d, int noOfDigits)
        {
            double abs = Math.Abs(d);
            int left = abs < 1 ? 1 : (int)(Math.Log10(abs) + 1);
    
            int usedDigits = 0;
    
            StringBuilder sb = new StringBuilder();
            for(; usedDigits < left; usedDigits++)
            {
                sb.Append("0");
            }
            if(usedDigits < noOfDigits)
            {
                sb.Append(".");
                for(; usedDigits < noOfDigits; usedDigits++)
                {
                    sb.Append("0");
                }
            }
            return d.ToString(sb.ToString());
        }
    

提交回复
热议问题