将双精度舍入到 x 位有效数字 [英] Round a double to x significant figures

查看:24
本文介绍了将双精度舍入到 x 位有效数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个双精度 (234.004223) 等,我想在 C# 中将其四舍五入为 x 位有效数字.

If I have a double (234.004223), etc., I would like to round this to x significant digits in C#.

到目前为止,我只能找到四舍五入到 x 位小数的方法,但是如果数字中有任何 0,这只会删除精度.

So far I can only find ways to round to x decimal places, but this simply removes the precision if there are any 0s in the number.

例如,0.086 到一位小数变为 0.1,但我希望它保持在 0.08.

For example, 0.086 to one decimal place becomes 0.1, but I would like it to stay at 0.08.

推荐答案

该框架没有内置函数来舍入(或截断,如您的示例)为多个有效数字.但是,您可以执行此操作的一种方法是缩放您的数字,以便您的第一个有效数字正好在小数点之后,舍入(或截断),然后再缩小.以下代码应该可以解决问题:

The framework doesn't have a built-in function to round (or truncate, as in your example) to a number of significant digits. One way you can do this, though, is to scale your number so that your first significant digit is right after the decimal point, round (or truncate), then scale back. The following code should do the trick:

static double RoundToSignificantDigits(this double d, int digits){
    if(d == 0)
        return 0;

    double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1);
    return scale * Math.Round(d / scale, digits);
}

如果,如在您的示例中,您确实想截断,那么您需要:

If, as in your example, you really want to truncate, then you want:

static double TruncateToSignificantDigits(this double d, int digits){
    if(d == 0)
        return 0;

    double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1 - digits);
    return scale * Math.Truncate(d / scale);
}

这篇关于将双精度舍入到 x 位有效数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆