gpt4 book ai didi

c# - 四舍五入到 x 有效数字

转载 作者:IT王子 更新时间:2023-10-29 03:44:21 27 4
gpt4 key购买 nike

如果我有 double (234.004223) 等,我想在 C# 中将其四舍五入为 x 位有效数字。

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

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

最佳答案

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

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);
}

如果像您的示例一样,您确实想要截断,那么您想要:

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);
}

关于c# - 四舍五入到 x 有效数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/374316/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com