Thursday, September 8, 2011

C# - Round To Significant Digits

Here's a quick and easy way in C# to round a double value to the nth significant digit:
 double RoundToSignificantDigits(double d, int digits)  
 {  
   // nothing to do if the value is zero  
   if (d == 0.0) return d;  
   double scale = Math.Pow(10, Math.Floor(Math.Log10(d)) + 1);  
   return scale * Math.Round(d / scale, digits);  
 }  
Or as Chris R. pointed out in the comments (thanks Chris), you may want to include Math.Abs(d) to ensure it works for negative values:
 double RoundToSignificantDigits(double d, int digits)  
 {  
   // nothing to do if the value is zero  
   if (d == 0.0) return d;  
   double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1);  
   return scale * Math.Round(d / scale, digits);  
 }  

1 comment:

Chris R said...

It should be Math.Log10(Math.Abs(d)) as otherwise it won't work with negative numbers...