我知道我们可以显示小数到一定的位数(如果位数是固定的)。例如,我们可以使用 String.Format
最多显示 2 个地方:
String.Format("{0:0.00}", 123.4567);
但我们的要求是,我们必须从数据库中获取小数位的位数,并显示小数点到该位的小数值。例如:
int n=no of decimal places
我想写这样的东西:
String.Format("{0:0.n}", 123.4567);
任何建议都会有很大帮助。
添加注释:String.Format
四舍五入数字。我正在寻找可以省略剩余数字的东西。
最佳答案
也许:
int n = 3;
string format = String.Format("{{0:0.{0}}}", new string('0', n));
Console.Write(String.Format(format, 123.4567)); // 123,457
作为方法:
public static string FormatNumber(double d, int decimalPlaces)
{
string format = String.Format("{{0:0.{0}}}", new string('0', decimalPlaces));
return String.Format(format, d);
}
或者更简单,使用 ToString
+ N
format specifier :
public static string FormatNumber(double d, int decimalPlaces)
{
return d.ToString("N" + decimalPlaces);
}
如果您不想要默认的舍入行为,但只想截断剩余的小数位:
public static string FormatNumberNoRounding(double d, int decimalPlaces)
{
double factor = Math.Pow(10, decimalPlaces);
double truncated = Math.Floor(d * factor) / factor;
return truncated.ToString();
}
关于c# - 在 C# 中显示小数到第 n 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26060882/