Programming Tips - Java: Format a number with two decimal places

Date: 2013aug30 Date: 2025jul11 Language: Java Q. Java: Format a number with two decimal places (eg dollars and cents) A. Use DecimalFormat() with "#.##". For floats:
String twoDecimal(final float f) { return new DecimalFormat("#.##").format(f); }
And for doubles its exactly the same:
String twoDecimal(final double d) { return new DecimalFormat("#.##").format(d); }
Example use:
void exampleUse() { System.out.println("value=" + twoDecimal(45.123456)); }