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.
source to share
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);
source to share
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.
source to share