Microsoft .Net frame work doesn't have any number in function to a double to a significant digits. This can be achievable by the following:
Scale your number scale so that so that your first significant digit is right after the decimal point, round (or truncate), then scale back. The following code should do the trick:
static double RoundToSignificantDigits(this double d, int digits)
{
double scale = Math.Pow(10, Math.Floor(Math.Log10(d)) + 1);
return scale * Math.Round(d / scale, digits);
}
To Truncate:
static double TruncateToSignificantDigits(this double d, int digits)
{
double scale = Math.Pow(10, Math.Floor(Math.Log10(d)) + 1 - digits);
return scale * Math.Truncate(d / scale);
}
Tuesday, March 31, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment