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

亡梦爱人 提交于 2019-12-04 18:00:21

问题


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.


回答1:


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);



回答2:


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.




回答3:


You can do it using String.format

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



回答4:


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



回答5:


ِEasiest way:

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



回答6:


It may be best to acquire your percent formatter through NumberFormat.getInstance(Locale locale) and using the setMinimumFractionDigits methods (and maybe the others).




回答7:


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

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


来源:https://stackoverflow.com/questions/26954443/how-do-i-format-my-percent-variable-to-2-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!