如何将百分比变量的格式设置为两位小数?
问题描述:
该程序基本上是在处理文本文件,读取数据和执行功能:
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(" ");
}
我想将百分比值格式化为2个小数位,但因为它位于内部
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.
答
Elliot的答案当然是正确的,但出于完整性考虑,值得注意的是如果您不想立即打印该值,而是保留String以作其他用途,则可以使用 DecimalFormat
类:
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);