Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round a double to 3 significant figures

Tags:

java

rounding

Does anybody know how I can round a double value to 3 significant figures like the examples on this website

http://www.purplemath.com/modules/rounding2.htm

like image 932
mh377 Avatar asked Sep 25 '11 21:09

mh377


People also ask

How do you round up to 3 significant figures?

We round a number to three significant figures in the same way that we would round to three decimal places. We count from the first non-zero digit for three digits. We then round the last digit. We fill in any remaining places to the right of the decimal point with zeros.

What does 2 significant figures mean?

For example, if 1254 is rounded to 2 significant figures, then 5 and 4 are replaced to 0 so that it will be 1300. For a number with the decimal point in rounding, remove the digits after the n digit. For example, if 14.895 is rounded to 3 significant figures, then the digits after 8 are removed so that it will be 14.9.


2 Answers

double d = ...; BigDecimal bd = new BigDecimal(d); bd = bd.round(new MathContext(3)); double rounded = bd.doubleValue(); 
like image 156
Sean Owen Avatar answered Oct 03 '22 00:10

Sean Owen


If you want to do it by hand:

import java.lang.Math;  public class SigDig {    public static void main(String[] args) {     System.out.println("   -123.456   rounded up   to 2 sig figures is " + sigDigRounder(-123.456, 2,  1));     System.out.println("     -0.03394 rounded down to 3 sig figures is " + sigDigRounder(-0.03394, 3, -1));     System.out.println("    474       rounded up   to 2 sig figures is " + sigDigRounder(474, 2,  1));     System.out.println("3004001       rounded down to 4 sig figures is " + sigDigRounder(3004001, 4, -1));   }    public static double sigDigRounder(double value, int nSigDig, int dir) {      double intermediate = value/Math.pow(10,Math.floor(Math.log10(Math.abs(value)))-(nSigDig-1));      if(dir > 0)      intermediate = Math.ceil(intermediate);     else if (dir< 0) intermediate = Math.floor(intermediate);     else             intermediate = Math.round(intermediate);      double result = intermediate * Math.pow(10,Math.floor(Math.log10(Math.abs(value)))-(nSigDig-1));      return(result);    } } 

The above method rounds a double to a desired number of significant figures, handles negative numbers, and can be explicitly told to round up or down

like image 40
awwsmm Avatar answered Oct 02 '22 23:10

awwsmm