Skip to content

Instantly share code, notes, and snippets.

@awwsmm
Created November 9, 2017 14:27
Show Gist options
  • Save awwsmm/b9e8a95c0b4fcf8e7cf2582d5374d29e to your computer and use it in GitHub Desktop.
Save awwsmm/b9e8a95c0b4fcf8e7cf2582d5374d29e to your computer and use it in GitHub Desktop.
Round a double to any number of significant figures, and control whether the number is rounded up or down
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment