How do I format a percentage variable to two decimal places?

This program mainly works with text files, reads data and performs the 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 percentage value to two decimal places, but since inside the while loop, I cannot use printf.

+7


source to share


7 replies


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



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

      

+9


source


You can use formatted output like,

System.out.printf("Percentage In Exam: %.2f%%%n", percent);

      

Formatter syntax describes precision as



accuracy

For common argument types, precision is the maximum number of characters that will be written to the output.

For floating point conversions, 'e', ​​'E', and 'f', precision is the number of digits after the decimal point. If the conversion is "g" or "G", then the precision is the total number of digits in the resulting value after rounding. If the conversion is "a" or "A", then the precision is not required.

The double percentage %%

becomes a literal percentage, and %n

a new line.

+8


source


You can do it using String.format

System.out.println(String.format("%s%.2f%s","Percentage In Exam: " ,percent,"%"));

      

+2


source


The easiest way:

   System.out.println(Math.floor(percent*100)/100);

      

0


source


Your best bet is to get your percentage formatter through NumberFormat.getInstance(Locale locale)

and using methods setMinimumFractionDigits

(and possibly others).

0


source


If the number is already in two decimal places, the simplest way would be to concatenate the number into a string like this:

System.out.println("" +percent+ "%");

      

0


source


NumberFormat percentageFormat = NumberFormat.getPercentInstance();
percentageFormat.setMinimumFractionDigits(2);

      

0


source







All Articles