c# - 在 C# 中显示小数到第 n 位

标签 c#

我知道我们可以显示小数到一定的位数(如果位数是固定的)。例如,我们可以使用 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/

相关文章:

c# - 如何从 .NET 代码向 .NET Windows 服务发送自定义命令?

c# - 为什么 HttpClient 只允许异步调用? C#

c# - json.NET 反序列化 2D 数组时抛出 InvalidCastException

c# - 静态初始化器中的 Task.Run

c# - WPF 不活动和事件

c# - 获取包含表的数据库列表的有效方法

c# - 如何处理IIS回收

c# - 在 .net 中使用 FFmpeg?

c# - 如何在 C# 中将 DataTable 转换为通用列表

c# - WPF控件中是否有向上/向下组合按钮?