【问题标题】:Java calculate percentage based on items in array listJava根据数组列表中的项目计算百分比
【发布时间】:2015-02-06 12:46:52
【问题描述】:

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

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。但是当我打印出总数时,它确实返回了总数。

有什么想法吗?

提前致谢。

【问题讨论】:

    标签: java math for-loop arraylist


    【解决方案1】:

    % = Value / Total * 100

    所以计算应该是:

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

    【讨论】:

      【解决方案2】:

      很可能你所有的分数都小于 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
      

      【讨论】:

      • 假设我希望它像 33。通过使用 *100,我最后还需要除以 10?
      • @IWasSoLost 如果要显示一位精度,您只需要 x10 和 /10.0,否则只需使用 long 而不是 double
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 2013-10-17
      相关资源
      最近更新 更多