有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我怎样才能让它执行到小数点后两位,作为长小数点

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) 个答案

  1. # 1 楼答案

    把一个数字乘以1,或者对一个你知道是整数的量调用Math.round是没有意义的。保持简单

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

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

  2. # 2 楼答案

    试着改用printf

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

    你可以用^{}formatted output^{}一样

    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%.