如何显示具有给定小数位数的数字

时间:2014-05-28 08:54:31

标签: c# string iteration

我写关于添加0的函数用于以字符串格式添加小数位,如此

   Function String DtoS_ (decimal value ,int decimalplace)
   {
     decimal result = value;
     String format = ""#,##0";
     if(decimalplace> 0)
     {
       format += ".";
       for( int i =0;i<decimalplace;i++)
       {
         format +="0"; 
       }
     }  

     return result.ToString(format); //e.g. "#,##0.00"
   }

我想知道还有其他方法/技巧可以不需要在上面使用循环或while循环进行迭代,在此先感谢。

3 个答案:

答案 0 :(得分:0)

您可以创建一个新的字符串,其中包含您需要的零数,如下所示:

   // your existing code
   // replace the for with this approach
   temp = new String('0', decimalplace);
   format = "." + temp;

答案 1 :(得分:0)

可能你在寻找什么:

    private static string DtoS2(decimal value, int decimalPlaces )
    {
        var format = decimalPlaces>0 ? "#,##0." + new string('0', decimalPlaces) : "#,##0";
        var result = value.ToString(format);
        return result;
    }

它的作用是根据小数位创建格式字符串。

最后,你非常接近。 new string('0', decimalPlaces)完全取决于您所寻找的内容,而不是循环。

答案 2 :(得分:0)

你可以用这个

decimal d = 1m;
int decimalPlaces = 2;
string format = decimalPlaces == 0 
            ? "#,##" 
            : "#,##." + new string('0', decimalPlaces);
string result = d.ToString(format); // 1.00