Decimal group seperator for the fractional part

五迷三道 提交于 2019-12-02 10:38:41

A little clunky, and it won't work for scientific numbers but here is a try:

class Program
{
    static void Main(string[] args)
    {
        var π=Math.PI*10000;

        Debug.WriteLine(Display(π));
        // 31,415.926,535,897,931,899
    }

    static string Display(double x)
    {
        int s=Math.Sign(x);
        x=Math.Abs(x);
        StringBuilder text=new StringBuilder();
        var y=Math.Truncate(x);
        text.Append((s*y).ToString("#,#"));
        x-=y;
        if (x>0)
        {
            // 15 decimal places is max reasonable precision
            y=Math.Truncate(x*Math.Pow(10, 15));
            text.Append(".");
            text.Append(y.ToString("#,#").TrimEnd('0'));
        }
        return text.ToString();
    }

}

It might be best to work with the string generated by your .ToString():

class Program
{
    static string InsertSeparators(string s)
    {
        string decSeparator = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;

        int separatorPos = s.IndexOf(decSeparator);
        if (separatorPos >= 0)
        {
            string decPart = s.Substring(separatorPos + decSeparator.Length);
            // split the string into parts of 3 or less characters
            List<String> parts = new List<String>();
            for (int i = 0; i < decPart.Length; i += 3)
            {
                string part = "";
                for (int j = 0; (j < 3) && (i + j < decPart.Length); j++)
                {
                    part += decPart[i + j];
                }
                parts.Add(part);
            }
            string groupSeparator = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator;
            s = s.Substring(0, separatorPos) + decSeparator + String.Join(groupSeparator, parts);
        }

        return s;

    }

    static void Main(string[] args)
    {

        for (int n = 0; n < 15; n++)
        {
            string s = Math.PI.ToString("0." + new string('#', n));
            Console.WriteLine(InsertSeparators(s));
        }

        Console.ReadLine();

    }
}

Outputs:

3
3.1
3.14
3.142
3.141,6
3.141,59
3.141,593
3.141,592,7
3.141,592,65
3.141,592,654
3.141,592,653,6
3.141,592,653,59
3.141,592,653,59
3.141,592,653,589,8
3.141,592,653,589,79

OK, not my strong side, but I guess this may be my best bet:

 string input = Math.PI.ToString();
 string decSeparator = System.Threading.Thread.CurrentThread
                      .CurrentCulture.NumberFormat.NumberGroupSeparator;
 Regex RX = new Regex(@"([0-9]{3})");
 string result  = RX.Replace(input , @"$1" + decSeparator);

Thanks for listening..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!