Date: 2013aug30
Update: 2025jul19
Language: Java
Q. Java: Format a number with two decimal places
(eg dollars and cents)
A. Use DecimalFormat() with "#.##".
For floats:
static String twoDecimal(final float f) {
return new DecimalFormat("#.##").format(f);
}
And for doubles its exactly the same:
static String twoDecimal(final double d) {
return new DecimalFormat("#.##").format(d);
}
Full example use:
import java.text.DecimalFormat;
class Demo {
static String twoDecimal(final float f) {
return new DecimalFormat("#.##").format(f);
}
static String twoDecimal(final double d) {
return new DecimalFormat("#.##").format(d);
}
public static void main(String[] args) {
System.out.println("value=" + twoDecimal(45.123456));
}
}
Will output:
value=45.12