Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.


C#
double d;
double f;

...

if(d != f)
{
}
Posted
Comments
Apfelmuuus 7-Dec-12 8:13am    
I don't get what this code is about but if you just want to check if two floating values are different in n decimal places transform the value to an int like : <br>
round(10^n*d) != round(10^n*f) <br> or what do you want to do?
<br> Regards Martin

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:

C#
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:

C#
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
 
Share this answer
 
Use System.Math.Round(double value, int digits) where digits specifies the number of fractional digits in the return value. So your comparison becomes:
C#
double d;
double f;
 
...
 
if (System.Math.Round(d, 11) != System.Math.Round(f, 11))
{
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900