回合双为x显著数字 [英] Round a double to x significant figures

查看:108
本文介绍了回合双为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位小数,但这只是删除了precision是否有数量的任何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到1位小数变为0.1,但我想它留0.08。

e.g. 0.086 to 1 decimal place becomes 0.1 but I would like it to stay 0.08.

推荐答案

该框架不具有一个内置函数来圆(或截断,因为在你的例子),以一些显著数字。你可以做到这一点的方法之一,不过,是扩展你的电话号码,这样你的第一个显著位数是小数点之后,圆形(或截断),然后缩减。下面code应该做的伎俩:

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天全站免登陆