c# how to String.Format decimal with unlimited decimal places?

前端 未结 3 1443
醉梦人生
醉梦人生 2020-12-06 18:18

I need to convert a decimal number to formatted string with thousand groups and unlimited (variable) decimal numbers:


    1234 -> \"1,234\"
    1234.567 -> \"1,2         


        
3条回答
  •  春和景丽
    2020-12-06 19:09

    this should do the trick

    string DecimalToDecimalsString(decimal input_num)
            {            
                decimal d_integer = Math.Truncate(input_num); // = 1234,0000...
                decimal d_decimals = input_num-d_integer; // = 0,5678...
    
                while (Math.Truncate(d_decimals) != d_decimals)
                    d_decimals *= 10; //remove decimals
    
                string s_integer = String.Format("{0:#,#}", d_integer);
                string s_decimals = String.Format("{0:#}", d_decimals);
    
                return s_integer + "." + s_decimals;
            }
    

    replacing decimal with other types should work too.

提交回复
热议问题