c# - 如何在 C# 中以人性化的方式舍入 double ?

标签 c# math floating-point rounding

在我的 C# 程序中,我有一个从一些计算中获得的 double,它的值类似于 0,139990,0079996 但是此值必须呈现给人类,因此最好分别显示为 0,140,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/

相关文章:

c# - 如何在 ASP.net Core 中实现 dataTables 服务器端分页/搜索/排序

c# - 如何检查 T4 模板文件中实体属性的数据类型

javascript - 我怎样才能从这个 Angular 得到一个方向? (需要一些数学帮助)

c++ - 有与没有额外变量的奇怪浮点行为,为什么?

c++ - 为什么 Visual Studio 的调试不将我的 float 显示为简单的十进制值

c# - 使用 MVVM 限制 WPF 中绑定(bind)到 DataGrid 的属性

c# - 如何在将 ItemsSource 绑定(bind)到列表的 TabControl 中获取 TabItems?

php - 将数学放入 sql 查询中

math - float 学运算是否被破坏?

javascript - 我如何在 JavaScript 中四舍五入一个数字?