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
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.
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.
double d = ...; BigDecimal bd = new BigDecimal(d); bd = bd.round(new MathContext(3)); double rounded = bd.doubleValue();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With