0

I write function about add 0 for use to add decimal place in string format like this

   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"
   }

I want to know that is there other ways/trick to iteration that don't need to use for loop or while loop above , Thanks in advance.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
user3682728
  • 467
  • 3
  • 7
  • I want to know that is there other ways you could rephrase your question/problem. But AFAI understand, you could try going with Linq. – Kilazur May 28 '14 at 08:56
  • http://stackoverflow.com/questions/411752/best-way-to-repeat-a-character-in-c-sharp – unlimit May 28 '14 at 08:58
  • Please see duplicate or read [MSDN: Standard Numeric Format Strings](http://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx#FFormatString). Decimal format strings can be followed by a number specifying the required number of decimals, like `-29541.ToString("F3")` yields `-29541.000`. You can pass your `decimalplace` into the format string. Use `N` instead of `F` to display thousand separators. – CodeCaster May 28 '14 at 09:13
  • Sorry about my poor English writing skill. "new string('0', decimalPlaces);" is exactly what I looking for(not Decimal format),but I don't know keyword to search so I asked the question by write that function as example. Thanks all. – user3682728 May 28 '14 at 09:26

3 Answers3

0

You can create a new string with the number of zeros you need as follows:

   // your existing code
   // replace the for with this approach
   temp = new String('0', decimalplace);
   format = "." + temp;
miltonb
  • 6,905
  • 8
  • 45
  • 55
0

Probably what you are looking for:

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

What it does is to create the format string depending on the decimal places.

At the end, you were very close. Instead of the loop, the new string('0', decimalPlaces) does exactly what you were looking for.

AcidJunkie
  • 1,878
  • 18
  • 21
0

You could use this

decimal d = 1m;
int decimalPlaces = 2;
string format = decimalPlaces == 0 
            ? "#,##" 
            : "#,##." + new string('0', decimalPlaces);
string result = d.ToString(format); // 1.00
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939