Update . Having these mixed requirements (i.e. at least 2 digits after the decimal point should be displayed, but as many as you like) is not trivially implemented, but you can get closer:
Combine stripTrailingZeros() with DecimalFormat to get the desired behavior (or close to it):
DecimalFormat df = new DecimalFormat("0.00########") String formatted = df.format(bigDecimal.stripTrailingZeros())
This will format any BigDecimal value with at least two digits after the decimal point and up to ten digits after the decimal point if this improves accuracy.
BigDecimal values with more than 10 digits after the decimal point is still disabled:
input | output
----------------- + ----------
1.20000 | 1.20
1.23000 | 1.23
1.2301 | 1.2301
1.230001000 | 1.230001
1.2300000000001 | 1.23
Original answer:
If you always want to have exactly 2 digits after the decimal point and know that you will not lose accuracy in this way, you can call setScale(2, RoundingMode.UNNECESSARY) :
System.out.println(new BigDecimal("1.23000").setScale(2, RoundingMode.UNNECESSARY));
This code will print 1.23 . Note that this will raise an ArithmeticException when rounding is required (i.e., anything after the first two digits is non-zero).
If your values may have higher precision and you want to apply some rounding, simply replace RoundingMode.UNNECESSARY with the appropriate value :
System.out.println(new BigDecimal("1.2301").setScale(2, RoundingMode.CEILING));
It will open 1.24 .
If you don't know the exact number of digits, but want as little as possible (i.e. you want the smallest possible scale for your BigDecimal ), calling stripTrailingZeros() will do exactly what you want:
System.out.println(new BigDecimal("1.230001000").stripTrailingZeros();
This will print 1.230001 .