在C#中四舍五入双重价值 [英] Rounding double values in C#
问题描述
我想在C#双值的舍入方法。它需要能够为double值四舍五入到任何舍入precision值。手头上我的code如下:
I want a rounding method on double values in C#. It needs to be able to round a double value to any rounding precision value. My code on hand looks like:
public static double RoundI(double number, double roundingInterval) {
if (roundingInterval == 0.0)
{
return;
}
double intv = Math.Abs(roundingInterval);
double sign = Math.Sign(number);
double val = Math.Abs(number);
double valIntvRatio = val / intv;
double k = Math.Floor(valIntvRatio);
double m = valIntvRatio - k;
bool mGreaterThanMidPoint = ((m - 0.5) >= 1e-14) ? true : false;
bool mInMidpoint = (Math.Abs(m - 0.5) < 1e-14) ? true : false;
return (mGreaterThanMidPoint || mInMidpoint) ? sign * ((k + 1) * intv) : sign * (k * intv);
}
所以RoundI(100,3)应该给99和RoundI(1.2345,0.001),应给予1.235。
So RoundI(100, 3) should give 99 and RoundI(1.2345, 0.001) should give 1.235.
问题是,RoundI(1.275,0.01)返回1.27,而不是1.28。这是执行双重valIntvRatio = VAL / INTV时因为,即双valIntvRatio = 1.275 / 0.01,它给0.12749999999999。我知道这是在任何编程语言重新双击presentation一个问题。我的问题是,有没有一个标准的code到做这样的事情,而不需要担心precision双?在这里,我设置了耐1E-14,但是这个太限制对于这个问题,我不知道什么是要设置正确的耐受性。感谢您的任何帮助。
The problem is, RoundI(1.275, 0.01) returns 1.27, rather than 1.28. This is because when executing double valIntvRatio = val/intv, that is, double valIntvRatio = 1.275 / 0.01, it gives 0.12749999999999. I know this is a problem with double representation in any programming language. My question is, is there a standard code to do things like this, without the need to worry about precision on double? Here I set the tolerant to 1e-14, but this is too restrict for this problem and I don't know what is the correct tolerance to be set. Thank you for any help.
推荐答案
使用示例小数
,为的基比的指出
double d = 1.275;
Math.Round(d, 2); // 1.27
Math.Round((decimal)d, 2); // 1.28
这篇关于在C#中四舍五入双重价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!