Advertisement
Guest User

isequal method for numbers

a guest
Aug 25th, 2011
640
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.24 KB | None | 0 0
  1.  
  2.     /// <summary>
  3.         /// The following method compares any 2 objects and test if they are equal.
  4.         /// It will also compare equality of numbers in a very special way.
  5.         /// Examples:
  6.         ///    isequal(Int64.MaxValue, Int64.MaxValue) //is true
  7.         ///    isequal(Int64.MaxValue, Int64.MaxValue-1) //is false
  8.         ///    isequal(123, 123.0) //is true
  9.         ///    isequal(654f, 654d) //is true
  10.         /// </summary>
  11.     public bool isequal(object a, object b)
  12.         {
  13.             if (a == null && b == null) //both are null
  14.                 return true;
  15.             if (a == null || b == null) //one is null, the other isn't
  16.                 return false;
  17.  
  18.             if (IsNumber(a) && IsNumber(b))
  19.             {
  20.                 if (isFloatingPoint(a) || isFloatingPoint(b))
  21.                 {
  22.                     double da, db;
  23.                     if (Double.TryParse(a.ToString(), out da) && Double.TryParse(b.ToString(), out db))
  24.                         return Math.Abs(da - db) < 0.000001;
  25.                 }
  26.                 else
  27.                 {
  28.                     if (a.ToString().StartsWith("-") || b.ToString().StartsWith("-"))
  29.                         return Convert.ToInt64(a) == Convert.ToInt64(b);
  30.                     else
  31.                         return Convert.ToUInt64(a) == Convert.ToUInt64(b);
  32.                 }
  33.             }
  34.  
  35.             return a.Equals(b);
  36.         }
  37.  
  38.         private bool isFloatingPoint(object value)
  39.         {
  40.             if (value is float) return true;
  41.             if (value is double) return true;
  42.             if (value is decimal) return true;
  43.             return false;
  44.         }
  45.  
  46.         private bool IsNumber(object value)
  47.         {
  48.             if (value is sbyte) return true;
  49.             if (value is byte) return true;
  50.             if (value is short) return true;
  51.             if (value is ushort) return true;
  52.             if (value is int) return true;
  53.             if (value is uint) return true;
  54.             if (value is long) return true;
  55.             if (value is ulong) return true;
  56.             if (value is float) return true;
  57.             if (value is double) return true;
  58.             if (value is decimal) return true;
  59.             return false;
  60.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement