Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 648
Vishal Jhoon Avatar asked Nov 16 '14 06:11

Vishal Jhoon


People also ask

How do you write a percentage in two decimal places?

So 25% is 25/100, or 0.25. To convert a decimal to a percentage, multiply by 100 (just move the decimal point 2 places to the right). For example, 0.065 = 6.5% and 3.75 = 375%. To find a percentage of a number, say 30% of 40, just multiply.

How do you display upto 2 decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

How do you print a float value up to 2 decimal places?

we now see that the format specifier "%. 2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places. Similarly, had we used "%. 3f", x would have been printed rounded to 3 decimal places.


2 Answers

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); 
like image 62
Mureinik Avatar answered Oct 05 '22 16:10

Mureinik


You could use formatted output like,

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

The Formatter syntax describes precision as

Precision

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

For the floating-point conversions 'e', 'E', and 'f' the precision is the number of digits after the decimal separator. If the conversion is 'g' or 'G', then the precision is the total number of digits in the resulting magnitude after rounding. If the conversion is 'a' or 'A', then the precision must not be specified.

The double percent %% becomes a percent literal, and the %n is a newline.

like image 20
Elliott Frisch Avatar answered Oct 05 '22 17:10

Elliott Frisch