Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
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
Comments
Apfelmuuus at 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: bad
good
Please Sign up or sign in to vote.

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
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

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))
{
}
  Permalink  

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

  Print Answers RSS
0 CHill60 365
1 Sergey Alexandrovich Kryukov 245
2 Peter Leow 180
3 CPallini 150
4 Zoltán Zörgő 150
0 Sergey Alexandrovich Kryukov 9,208
1 OriginalGriff 6,796
2 Peter Leow 4,417
3 Zoltán Zörgő 3,849
4 CHill60 2,702


Advertise | Privacy | Mobile
Web03 | 2.8.150128.1 | Last Updated 7 Dec 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100