How can we display an output of float data with 2 decimal places in java Please help
Can I do it with system.out.println?how to use format double to 2 decimal places java?
You can use the printf method, for example:
System.out.printf("%.2f", value);
The %.2f syntax tells Java to return your variable (value) with 2 decimal places (.2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
Or You can use DecimalFormat display an output of float data with 2 decimal places in java. 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.
There are 7 ways to format double to 2 decimal places in java
Using String's format() method.
- Using System.out.printf.
- Using Formatter.
- Using BigDecimal.
- Using DecimalFormat.
- Using NumberFormat.
- Using Apache common library.