如何将百分比变量的格式设置为两位小数? [英] How do I format my percent variable to 2 decimal places?

查看:103
本文介绍了如何将百分比变量的格式设置为两位小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序基本上是在处理文本文件,读取数据和执行功能:

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

这篇关于如何将百分比变量的格式设置为两位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆