Show decimal of a double only when needed
The DecimalFormat with the # parameter is the way to go:
public static void main(String[] args) { double d1 = 1.234567; double d2 = 2; NumberFormat nf = new DecimalFormat("##.###"); System.out.println(nf.format(d1)); System.out.println(nf.format(d2)); }
Will result in
1.2352
Don't use doubles. You can lose some precision. Here's a general purpose function.
public static double round(double unrounded, int precision, int roundingMode){ BigDecimal bd = new BigDecimal(unrounded); BigDecimal rounded = bd.setScale(precision, roundingMode); return rounded.doubleValue();}
You can call it with
round(yourNumber, 3, BigDecimal.ROUND_HALF_UP);
"precision" being the number of decimal points you desire.
Try it
double amount = 1.234567 ; NumberFormat formatter = new DecimalFormat("##.###"); System.out.println("The Decimal Value is:"+formatter.format(amount));