Monday, March 30, 2009

Rounding double

Rounding Numbers
There are three basic ways to round numbers. The one that most people know is rounding to the nearest whole number, or to the nearest ten, but there are two other ways to round which are essentially very similar to this method. They are rounding to two (or three) deciml places and rounding to three (or four) significant figures.
Why do we need to round numbers?
You may see it reported that a TV program had 23 million viewers. This is not actually true because some of those viewers fell asleep half way through the program and some people lied about watching the program. The true number of viewers was somewhere between 22½ million and 23½ million and the published figure was rounded to the nearest million. Similarly if you used your calculator to find the square root of 1000, you would get something like:

√1000 = 31.622776601683793319988935444327

The most important digits are the 3, 1 and 6 at the beginning. The least important digits are the 3, 2 and 7 at the end. It is bad practice to write down all the digits that the calculator shows so we choose only to write down a few of the most important ones.
Rounding to the nearest ten and the nearest whole number
Looking at the number above, it should be seen that, to the nearest ten, the square root of 1000 is 30. The above number is between 30 and 40 and it is nearer to 30. This is an example of rounding down.
To the nearest whole number, the square root of 1000 is actually 32 because the number given above is closer to 32 than to 31. This is an example of rounding up.

Sample 1

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);
}

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);
}

* 2.22939393 -> 2.229
* 2.22977777 -> 2.229


Sample 2

double d = 2.22977777;
d = ( (double) ( (int) (d * 1000.0) ) ) / 1000.0 ;

No comments: