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
There's nothing wrong with the answer given by Sean Owen (https://stackoverflow.com/a/7548871/274677). However depending on your use case you might want to arrive at a String representation. In that case, IMO it is best to convert while still in BigDecimal space using:
bd.toPlainString();
... if that's your use case then you might be frustrated that the code adapted from Owen's answer will produce the following:
d = 0.99, significantDigits = 3 ==> 0.99
... instead of the strictly more accurate 0.990.
If such things are important in your use case then I suggest the following adaptation to Owen's answer ; you can obviously also return the BigDecimal itself instead of calling toPlainString() — I just provide it this way for completeness.
public static String setSignificanDigits(double value, int significantDigits) {
if (significantDigits < 0) throw new IllegalArgumentException();
// this is more precise than simply doing "new BigDecimal(value);"
BigDecimal bd = new BigDecimal(value, MathContext.DECIMAL64);
bd = bd.round(new MathContext(significantDigits, RoundingMode.HALF_UP));
final int precision = bd.precision();
if (precision < significantDigits)
bd = bd.setScale(bd.scale() + (significantDigits-precision));
return bd.toPlainString();
}