Java百分比计算没有处理,我无法弄清楚原因

时间:2014-09-24 23:22:52

标签: java android arrays math percentage

下面是一段代码:

System.out.println("Calc: " + totalMs[0] + " divided by " + totalTestMs + " times 100");
System.out.println("Calc 2: " + totalBits[0] + " divided by " + totalCount[0] + " divided by 1000000");

DecimalFormat df = new DecimalFormat("0.00");

String b1 = "0", b2 = "0", b3 = "0", b4 = "0", b5 = "0", b6 = "0", b7 = "0", b8 = "0", b9 = "0", b10 = "0";
String b1Pct = "0";

if (totalCount[0] > 0) { 
    b1Pct = df.format((totalMs[0]/totalTestMs)*100);
    b1 = df.format((totalBits[0]/totalCount[0])/1000000); 
}

Calc失败,Calc 2通过。上述系统打印显示的输出为:

enter image description here

如您所见,数字似乎正确传递。但是,当I System输出 b1Pct 结果时,它会显示“0.0”。在这种情况下它应该是22.73。

我确信这很简单,但我无法理解。更令人困惑的是,第二个是正确的!

1 个答案:

答案 0 :(得分:2)

看起来你正在对Calc进行整数除法。当你除去两个整数时,你得到一个整数,其余的被丢弃,即:

System.out.println("Integer divide: " + 40/100); //Result is 0

你需要将其中一个转换为浮点数,只需添加一个小数,即:

System.out.println("Decimal divide: " +  40/100.); //Result is .40
System.out.println("Cast divide: " + 40/((float)100)); //Result is .40

干杯!