27

I know that if we want to display a double as a two decimal digit, one would just have to use

public void DisplayTwoDecimal(double dbValue)
{
  Console.WriteLine(dbValue.ToString("0.00"));
}

But how to extend this to N decimal places, where N is determined by the user?

 public void DisplayNDecimal(double dbValue, int nDecimal)
    {
     // how to display
    }
Graviton
  • 81,782
  • 146
  • 424
  • 602

2 Answers2

61

Use "Nx" for x decimal digits.

 public void DisplayNDecimal(double dbValue, int nDecimal)
 {
   Console.WriteLine(dbValue.ToString("N" + nDecimal));
 }
Stefan
  • 14,530
  • 4
  • 55
  • 62
-3

I would use this:

public string DisplayNDecimal(double dbValue, int nDecimal)
{
    string decimalPoints = "0";
    if (nDecimal > 0)
    {
        decimalPoints += ".";
        for (int i = 0; i < nDecimal; i++)
            decimalPoints += "0";
    }
    return dbValue.ToString(decimalPoints);
}

:)

Here is it with StringBuilder (though probably not more efficient and definitely would require more resources)

public string DisplayNDecimal(double dbValue, int nDecimal)
{
    StringBuilder decimalPoints = new StringBuilder("0");
    if (nDecimal > 0)
    {
        decimalPoints.Append(".");
        for (int i = 0; i < nDecimal; i++)
            decimalPoints.Append("0");
    }
    return dbValue.ToString(decimalPoints.ToString());
}
nawfal
  • 70,104
  • 56
  • 326
  • 368
user1690294
  • 93
  • 1
  • 7