How to print a float with 2 decimal places in Java?
To print a float with 2 decimal places in Java, you can use the printf method and specify a format string with the %.2f format specifier. Here's an example:
float num = 3.14159265358979323846264338327950288419716939937510;
System.out.printf("%.2f", num);This will print the value of num with 2 decimal places, like this:
3.14You can also use the DecimalFormat class to format a float with a specific number of decimal places. Here's an example:
float num = 3.14159265358979323846264338327950288419716939937510;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(num));This will also print the value of num with 2 decimal places:
3.14