There\'s been a lot of questions on rounding by significant figures, and answers that that provides a new method to do the rounding, such as:
Rounding to an arbitrar
I found this nice way of doing it using String format. Apparently, users can specify maximum number of significant digits with a string format 'g' or 'G'. (http://developer.android.com/reference/java/util/Formatter.html)
This is if you just want to print it out.
public String toSignificantFiguresString(BigDecimal bd, int significantFigures){
return String.format("%."+significantFigures+"G", bd);
}
This is if you want to convert it:
public BigDecimal toSignificantFigures(BigDecimal bd, int significantFigures){
String s = String.format("%."+significantFigures+"G", bd);
BigDecimal result = new BigDecimal(s);
return result;
}
Here's an example of it in action:
BigDecimal bd = toSignificantFigures(BigDecimal.valueOf(12345678.123456789), 10);
System.out.println("bd: " + String.format("%f",bd));
NB: I'm using BigDecimal for calculation because double and float has a precision problems.)
Not quite right. To get it perfect:
public String toSignificantFiguresString(BigDecimal bd, int significantFigures ){
String test = String.format("%."+significantFigures+"G", bd);
if (test.contains("E+")){
test = String.format(Locale.US, "%.0f", Double.valueOf(String.format("%."+significantFigures+"G", bd)));
}
return test;
}