我如何才能将其执行到两位小数,以十进制长的形式出现

时间:2015-01-26 19:26:39

标签: java double

int ptstotal, ptsearned, ptssofar;
ptstotal= 1500;
ptsearned= 750;
ptssofar= 950;

System.out.println("The current percentage is "+(int)Math.round(ptsearned*1)/(double)(ptssofar)*100+"%.");

System.out.println("The current percentage is "+Math.round(ptsearned*1)/(double)ptssofar*100+"%.");

输出为长十进制78.96736805263%,只需要78.97%需要一些帮助

3 个答案:

答案 0 :(得分:1)

尝试使用printf

double value = (int)Math.round(ptsearned*1)/(double)(ptssofar)*100;
System.out.printf("The current percentage is %.2f %",value);

答案 1 :(得分:0)

您可以使用DecimalFormatformatted outputprintf(String, Object...)一样

DecimalFormat df = new DecimalFormat("###.00");
System.out.println("The current percentage is "
        + df.format(Math.round(ptsearned * 1) / (double) (ptssofar)
                * 100) + "%.");
System.out.printf("The current percentage is %.2f%%.%n",
        Math.round(ptsearned * 1) / (double) ptssofar * 100);

哪些输出(请求的)

The current percentage is 78.95%.
The current percentage is 78.95%.

答案 2 :(得分:0)

没有必要将数字乘以1,或者在您知道的整数数量上调用Math.round。保持简单。

double percentage = (double)ptsearned / ptssofar * 100;
System.out.format("The current percentage is %.2f%%%n", percentage);

在这里,您需要(double)来避免整数除法。然后,在格式字符串中,%.2f表示显示带有两个小数位的值。下一个%%将转换为百分号,最后%n转换为行分隔符。