Double.ToString with N Number of Decimal Places

Gra*_*ton 24 c#

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"));
}
Run Code Online (Sandbox Code Playgroud)

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
    }
Run Code Online (Sandbox Code Playgroud)

Ste*_*fan 56

使用"Nx"表示x十进制数字.

 public void DisplayNDecimal(double dbValue, int nDecimal)
 {
   Console.WriteLine(dbValue.ToString("N" + nDecimal));
 }
Run Code Online (Sandbox Code Playgroud)

  • 使用Nx的副作用是该数字将被格式化为千位分隔符,即"1,234.5600" (13认同)
  • 如果你不想要数千个分隔符,你可以使用`Fx` (8认同)