繁体   English   中英

Java百分比计算未处理,我不知道为什么

[英]Java percentage calculation not processing and I can't figure out why

以下是一段代码:

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通过。 上面的系统打印显示的输出是:

在此处输入图片说明

如您所见,这些数字似乎正确传递了。 但是,当我系统输出b1Pct结果时,其状态为“ 0.0”。 在这种情况下,应为22.73。

我敢肯定这很简单,但我无法弄清楚。 更令人困惑的是,第二个是正确的!

看来您要对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

干杯!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM