11,924,995 members (54,327 online)
Rate this:
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.

```double d;
double f;

...

if(d != f)
{
}```
Posted 7-Dec-12 2:39am
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

Rate this:

## Solution 1

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
Rate this:

## Solution 2

Use `System.Math.Round(double value, int digits)` where `digits` 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))
{
}
```

Top Experts
Last 24hrsThis month
 OriginalGriff 240 Jochen Arndt 190 Manas_Kumar 130 Richard Deeming 105 F-ES Sitecore 101
 OriginalGriff 7,471 KrunalRohit 4,538 Sergey Alexandrovich Kryukov 3,500 George Jonsson 2,905 Suvendu Shekhar Giri 2,271