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?
但是如何将它扩展到N位小数,其中N是由用户决定的?
public void DisplayNDecimal(double dbValue, int nDecimal)
{
// how to display
}
2 个解决方案
#1
50
Use "Nx" for x decimal digits.
用“Nx”表示x十进制数字。
public void DisplayNDecimal(double dbValue, int nDecimal)
{
Console.WriteLine(dbValue.ToString("N" + nDecimal));
}
#2
-4
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)
这里是StringBuilder(尽管可能不是更高效,而且绝对需要更多的资源)
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());
}
#1
50
Use "Nx" for x decimal digits.
用“Nx”表示x十进制数字。
public void DisplayNDecimal(double dbValue, int nDecimal)
{
Console.WriteLine(dbValue.ToString("N" + nDecimal));
}
#2
-4
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)
这里是StringBuilder(尽管可能不是更高效,而且绝对需要更多的资源)
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());
}