指定小数位数的条件 [英] Condition on specified number of decimal places
本文介绍了指定小数位数的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
哪种方法可以检查一定数量的小数位数。
例如:我想在11个十分位置检查d和f 。
double d;
double f;
...
if (d!= f)
{
}
解决方案
想到几种方式。
首先,我多年前使用的一个老技巧:将值乘以10,直到有效数字全部位于小数点的左侧,转换为整数值并进行比较。所以:
var precision = 11 跨度>;
double d2 = d *(precision * 10);
double f2 = f *(precision * 10);
int dWhole =( int )d2;
int fWhole =( int )f2;
return (dWhole == fWHole);
其次,也许我现在要做的是提供一种比较一定精度内的双值的方法,例如:
public class MathUtilities
{
public static readonly double DOUBLE_PRECISION = 5 * Double.Epsilon;
public static bool Equal( double d1, double d2){返回 Math.Abs(d1 - d2)< = DOUBLE_PRECISION; }
}
此时,要比较最多11个十进制数字,您需要使用适当小的''精度''值(而不是5 * Double.Epsilon我上面用过的,比如0.000 [...] 009
HTH
使用System.Math.Round(double value,int digits)
其中digits
指定返回值中的小数位数。所以你的比较变成:
double d;
double f;
...
if (System.Math.Round(d, 11 )!= System.Math.Round(f, 11 ))
{
}
Which is the best way to check the condition of a certain number of decimal places.
For example: I want to check d and f on 11 decimale places.
double d;
double f;
...
if(d != f)
{
}
解决方案
A couple of ways come to mind.
First, an old trick I used to use many years ago: multiply the values by 10 until the significant digits are all on the left of the decimal point, cast to integer values and compare those. So:
var precision = 11; double d2 = d*(precision*10); double f2 = f*(precision*10); int dWhole = (int)d2; int fWhole = (int)f2; return (dWhole==fWHole);
Secondly, and probably what I would do nowadays, is to provide a method that compares double values within a certain precision, such as this:
public class MathUtilities { public static readonly double DOUBLE_PRECISION = 5*Double.Epsilon; public static bool Equal(double d1, double d2) { return Math.Abs(d1 - d2) <= DOUBLE_PRECISION; } }
At this point, to compare up to 11 decimal digits, you need to use an appropriately small ''precision'' value (instead of the 5*Double.Epsilon I used above), like 0.000[...]009
HTH
UseSystem.Math.Round(double value, int digits)
wheredigits
specifies the number of fractional digits in the return value. So your comparison becomes:
double d; double f; ... if (System.Math.Round(d, 11) != System.Math.Round(f, 11)) { }
这篇关于指定小数位数的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文