Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round a double to x significant figures

If I have a double (234.004223), etc., I would like to round this to x significant digits in C#.

So far I can only find ways to round to x decimal places, but this simply removes the precision if there are any 0s in the number.

For example, 0.086 to one decimal place becomes 0.1, but I would like it to stay at 0.08.

like image 968
Rocco Avatar asked Dec 17 '08 11:12

Rocco


People also ask

How do you round up to 2 significant figures?

look at the digit after the first non-zero digit if rounding to two significant figures. draw a vertical line after the place value digit that is required. look at the next digit. if it's 5 or more, increase the previous digit by one.

How do you round 2 SF in Python?

Use the round() Function to Round a Number to the Given Significant Digit in Python. The round() function rounds the given floating values to the nearest integer or specified decimal position. We can use a negative number to round the integer to the significant floor value by assigning it to the round() function.

What is the rule for rounding sig figs when multiplying?

For multiplication and division use the following rule: The LEAST number of significant figures in any number of the problem determines the number of significant figures in the answer.

How do you round an answer to significant figures?

When rounding significant figures the standard rules of rounding numbers apply, except that non-significant digits to the left of the decimal are replaced with zeros. This calculator rounds down if the next digit is less than 5 and rounds up when the next digit is greater than or equal to 5.


1 Answers

The framework doesn't have a built-in function to round (or truncate, as in your example) to a number of significant digits. One way you can do this, though, is to scale your number 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){     if(d == 0)         return 0;      double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1);     return scale * Math.Round(d / scale, digits); } 

If, as in your example, you really want to truncate, then you want:

static double TruncateToSignificantDigits(this double d, int digits){     if(d == 0)         return 0;      double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1 - digits);     return scale * Math.Truncate(d / scale); } 
like image 154
P Daddy Avatar answered Oct 01 '22 13:10

P Daddy