C# – Round To Significant Digits

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 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Post navigation

Previous Post :   
Visit Us On LinkedinVisit Us On FacebookVisit Us On TwitterVisit Us On YoutubeCheck Our FeedVisit Us On Instagram