该程序基本上处理文本文件,读取数据并执行功能:
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(" ");
}
我想将百分比值格式化为小数点后两位,但由于它位于 while 循环内,所以我无法使用 printf。
埃利奥特的答案当然是正确的,但为了完整起见,值得注意的是,如果您不想立即打印该值,而是保留字符串用于其他用途,则可以使用DecimalFormat https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html class:
DecimalFormat df = new DecimalFormat("##.##%");
double percent = (mark / tm);
String formattedPercent = df.format(percent);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)