Dan
Dan

Reputation: 2344

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:

enter image description here

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!

Upvotes: 1

Views: 931

Answers (1)

Zaid Daghestani
Zaid Daghestani

Reputation: 8615

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!

Upvotes: 2

Related Questions