Java 根据数组列表中的项目计算百分比

Java calculate percentage based on items in array list

我在尝试根据数组列表计算百分比时遇到了一些问题。

int total = 0;
    double percentage = 0;
    for(int i = 0; i < accountList.size(); i++){
        total += Integer.parseInt(accountList.get(i).getTotalCount());
    }

    for(int j = 0; j < accountList.size(); j++){
        percentage = Math.round(Double.parseDouble(accountList.get(j).getTotalCount()) / (double)total);
        Log.i("PCT", String.valueOf(percentage));
    }

基本上第一个循环就是计算总数。然后对于第二个循环,我循环数组列表中的每个项目除以总数以获得百分比。

但是,当我尝试打印百分比时,我得到的是 0.0。但是当我打印出总数时,它确实返回了总数。

有什么想法吗?

提前致谢。

% = Value / Total * 100

所以计算应该是:

percentage = Math.round((Double.parseDouble(accountList.get(j).getTotalCount()) * 100.0) / (double)total);

很可能你所有的分数都小于 0.5,所以当你舍入派系时,你会不断得到 0

我怀疑你想打印 100 x 派系的百分比。

 long percentage = Math.round(100.0 * 
                Double.parseDouble(accountList.get(j).getTotalCount()) / total);

 long percentage = 100L*Integer.parseInt(accountList.get(j).getTotalCount()) / total;

使用整数结果可能并不理想。我建议像这样添加一个精度数字。

 double percentage = 1000L 
                     * Integer.parseInt(accountList.get(j).getTotalCount()) 
                     / total / 10.0;

乘以整数计算所需的 10 倍,除以 10.0 时可获得额外的精度。

例如

100 * 1 / 3 == 33
1000 * 1 / 3 / 10.0 == 33.3