How do I format my percent variable to 2 decimal places?

Vishal Jhoon picture Vishal Jhoon · Nov 16, 2014 · Viewed 29.2k times · Source

This program is basically working with text files, reading the data & performing functions:

while(s.hasNext()){
    name= s.next();

    mark= s.nextDouble();

    double percent= (mark / tm )*100  ;

    System.out.println("Student Name      : " +name );

    System.out.println("Percentage In Exam: " +percent+"%"); 

    System.out.println(" ");
}

I would like to format the percent value to 2 decimal places but since it's inside a while loop I cannot use the printf.

Answer

Mureinik picture Mureinik · Nov 16, 2014

Elliot's answer is of course correct, but for completeness' sake it's worth noting that if you don't want to print the value immediately, but instead hold the String for some other usage, you could use the DecimalFormat class:

DecimalFormat df = new DecimalFormat("##.##%");
double percent = (mark / tm);
String formattedPercent = df.format(percent);