简体   繁体   中英

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

A snippet of code is below:

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 fails and Calc 2 passes. The Output shown by the above System prints is:

在此处输入图片说明

As you can see the figures appear to be passing correctly. However, when I System output the b1Pct result it states "0.0". When in this case it should be 22.73.

I'm sure it's something simple but I can't figure it out. Even more confusing as the second one is correct!

It looks like you are doing integer division for Calc. When you divide two integers, you get an integer and the remainder is discarded, ie:

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

You need to cast one of them to floats are simply add a decimal, ie:

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

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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