限制数组中的小数位数

时间:2013-04-24 00:53:15

标签: java android arrays decimal-point

目前,此数组的输出具有太大的小数位。如何将此限制为2位小数?我的意思是数组'percentage1'。我已经看到了在线进行的方法,但我不明白如何将这些方法实现到代码中,如下所示。

int[] correct1 = {20, 20, 13, 15, 22, 18, 19, 21, 23, 25};
int[] incorrect1 = {2, 1, 5, 2, 2, 5, 8, 1, 0, 0};

    double[] percentage1 = new double[correct1.length];
    for(int a = 0; a < correct1.length; a++ ){ 
             percentage1[a] = (((double)correct1[a] / (correct1[a] + incorrect1[a]))*100);
        }

非常感谢任何帮助。感谢

2 个答案:

答案 0 :(得分:3)

请尝试添加DecimalFormat对象。

  1. 将其添加到循环的开头,它会声明您要查找的格式 - 小数点后两位:DecimalFormat df = new DecimalFormat("#.##");

  2. 使用format对其进行格式化,然后将其转换回double。您需要将其还原的原因是format返回一个String。

    percentage1 [a] = Double.valueOf(df.format((((double)correct1 [a] /(correct1 [a] + incorrect1 [a]))* 100)));

  3. 见下面的修订代码:

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] correct1 = {20, 20, 13, 15, 22, 18, 19, 21, 23, 25};
        int[] incorrect1 = {2, 1, 5, 2, 2, 5, 8, 1, 0, 0};
    
            double[] percentage1 = new double[correct1.length];
            DecimalFormat df = new DecimalFormat("#.##");
            for(int a = 0; a < correct1.length; a++ ){ 
                     percentage1[a] = Double.valueOf(df.format((((double)correct1[a] / (correct1[a] + incorrect1[a]))*100)));
                     System.out.println(percentage1[a]);
                }
    
    }
    

    示例结果:

    90.91
    95.24
    72.22
    88.24
    91.67
    78.26
    70.37
    95.45
    100.0
    100.0
    

答案 1 :(得分:1)

你做不到。双打没有小数位。他们有二进制位置。如果你想要小数位,你必须使用十进制基数,即由DecimalFormatBigDecimal创建的字符串。

证明here

相关问题