作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
如果我有 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/
如何在 C++ 中进行涉及有效数字的数学运算?我希望它能正确处理化学和物理实验的测量数据。一个例子:65/5 = 10。我需要去掉不需要的小数位并将一些数字替换为 0。 谢谢! 最佳答案 这应该可以满
这个任务看起来很简单 - 在输入时我得到测试数量 (numOfTests),然后是两个数字 (downBorder, upBorder) 和我必须找出这些数字(downBorder、upBorder)
如果我有 double (234.004223) 等,我想在 C# 中将其四舍五入为 x 位有效数字。 到目前为止,我只能找到舍入到 x 位小数的方法,但是如果数字中有任何 0,这只会删除精度。 例如
我是一名优秀的程序员,十分优秀!