在我的 C# 程序中,我有一个从一些计算中获得的 double
,它的值类似于 0,13999
或 0,0079996
但是此值必须呈现给人类,因此最好分别显示为 0,14
或 0,008
。
所以我需要对值进行四舍五入,但不知道精度如何 - 我只需要“扔掉那些噪音数字”。
我如何在我的代码中做到这一点?
澄清一下 - 我需要将 double
值四舍五入到编译时未知的精度 - 这需要在运行时确定。实现这一目标的良好启发式方法是什么?
最佳答案
您似乎想要输出一个与输入值差别不大的值,因此请尝试增加位数直到出现给定错误:
static double Round(double input, double errorDesired)
{
if (input == 0.0)
return 0.0;
for (int decimals = 0; decimals < 17; ++decimals)
{
var output = Math.Round(input, decimals);
var errorAchieved = Math.Abs((output - input) / input);
if (errorAchieved <= errorDesired)
return output;
}
return input;
}
}
static void Main(string[] args)
{
foreach (var input in new[] { 0.13999, 0.0079996, 0.12345 })
{
Console.WriteLine("{0} -> {1} (.1%)", input, Round(input, 0.001));
Console.WriteLine("{0} -> {1} (1%)", input, Round(input, 0.01));
Console.WriteLine("{0} -> {1} (10%)", input, Round(input, 0.1));
}
}
关于c# - 如何在 C# 中以人性化的方式舍入 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9079886/