Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 28th, 2012  |  syntax: None  |  size: 1.60 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Getting Exact precision of decimal places from a double in .NET 3.5
  2. double myDoubleValue = 50234.9489898997952932;
  3.        
  4. using System.Globalization;
  5.  
  6. class Program
  7. {
  8.     static void Main(string[] args)
  9.     {
  10.         double d = 50234.9489898997952932;
  11.         char probablyDot = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
  12.         string[] number = d.ToString().Split(probablyDot);
  13.  
  14.  
  15.         //Console.WriteLine(number[0] + probablyDot + number[1].Remove(4));
  16.  
  17.         Console.WriteLine(number[0] + probablyDot + (number.Length >1 ? (number[1].Length>4? number[1].Substring(0,4):number[1]): "0000"));
  18.         //Output: 50234.9489
  19.  
  20.         Console.ReadKey();
  21.     }
  22. }
  23.        
  24. double d = 50234.94895345345345;
  25. var Expected_result =  Double.Parse((Regex.Match(d.ToString(), "[+-]?\d*.\d{0,4}")).Value);
  26.        
  27. public static class DoubleEx
  28. {
  29.     public static double TruncateFraction(this double value, int fractionRound)
  30.     {
  31.         double factor = Math.Pow(10, fractionRound);
  32.         return Math.Truncate(value * factor) / factor;
  33.     }
  34. }
  35.        
  36. double foo = 50234.9489898997952932;
  37. double bar = foo.TruncateFraction(4);
  38.  
  39. Console.WriteLine(foo); //50234.9489898997952932
  40. Console.WriteLine(bar); //50234.9489
  41.        
  42. private static string TrimDecimalPlaces(double value, int numberOfDecimalPlaces)
  43. {
  44.     string valueString = value.ToString();
  45.  
  46.     if (!valueString.Contains(".")) return valueString;
  47.  
  48.     int indexOfDot = valueString.IndexOf(".");
  49.  
  50.     if ((indexOfDot + numberOfDecimalPlaces + 1) < valueString.Length)
  51.     {
  52.         return valueString.Remove(indexOfDot + numberOfDecimalPlaces + 1);
  53.     }
  54.     return valueString;
  55. }