Decimal group seperator for the fractional part

后端 未结 3 1263
误落风尘
误落风尘 2021-01-28 07:27

I wonder what would be the best way to format numbers so that the NumberGroupSeparator would work not only on the integer part to the left of the comma, but also on

3条回答
  •  萌比男神i
    2021-01-28 08:10

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

提交回复
热议问题