Java 如何将百分比变量格式化为小数点后两位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26954443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:34:10  来源:igfitidea点击:

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

javadecimalnumber-formatting

提问by Vishal Jhoon

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.

我想将百分比值格式化为 2 个小数位,但由于它在 while 循环内,我不能使用 printf。

回答by Elliott Frisch

You could use formatted output like,

您可以使用格式化输出,例如,

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

The Formatter syntaxdescribes precisionas

格式化语法描述精度

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.

精确

对于一般参数类型,精度是要写入输出的最大字符数。

对于浮点转换“e”、“E”和“f”,精度是小数点分隔符后的位数。如果转换为 'g' 或 'G',则精度是四舍五入后所得大小的总位数。如果转换为“a”或“A”,则不得指定精度。

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

双百分比%%变成百分比文字,而%n是换行符。

回答by Mureinik

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 DecimalFormatclass:

Elliot 的答案当然是正确的,但为了完整起见,值得注意的是,如果您不想立即打印该值,而是将 String 保留用于其他用途,则可以使用DecimalFormat该类:

DecimalFormat df = new DecimalFormat("##.##%");
double percent = (mark / tm);
String formattedPercent = df.format(percent);

回答by Xline

?Easiest way:

?最简单的方法:

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

回答by Diunicorn

You can do it using String.format

你可以使用 String.format

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

回答by Anthony Chuinard

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

最好通过NumberFormat.getInstance(Locale locale)并使用这些setMinimumFractionDigits方法(可能还有其他方法)来获取百分比格式器。

回答by Valerie Ogonor

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+ "%");

回答by Joe Almore

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