How to print a float with 2 decimal places in Java?
You can use the printf
method, like so:
System.out.printf("%.2f", val);
In short, the %.2f
syntax tells Java to return your variable (val
) with 2 decimal places (.2
) in decimal representation of a floating-point number (f
) from the start of the format specifier (%
).
There are other conversion characters you can use besides f
:
d
: decimal integero
: octal integere
: floating-point in scientific notation
You can use DecimalFormat
. One way to use it:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));
Another one is to construct it using the #.##
format.
I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.