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 1: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 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  
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  

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

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Shai Vashdi 576
1 Tadit Dash 215
2 Sergey Alexandrovich Kryukov 190
3 OriginalGriff 183
4 Peter Leow 130
0 Sergey Alexandrovich Kryukov 9,325
1 OriginalGriff 5,473
2 Peter Leow 4,150
3 Maciej Los 3,540
4 Abhinav S 3,333


Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 7 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid