Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

percentage of two int?

Tags:

java

int

decimal

I want to get two ints, one divided by the other to get a decimal or percentage. How can I get a percentage or decimal of these two ints? (I'm not sure if it is right.. I'm probably way off...) for example:

int correct = 25; int questionNum = 100; float percent = correct/questionNum *100; 

This is how I thought I could do it, but it didn't work... I want to make the decimal (if there is one) into a percent out of 100 for example in this case it is %25. any ideas anyone?

Here is the correct code (thanks to Salvatore Previti!):

float correct = 25; float questionNum = 100; float percent = (correct * 100.0f) / questionNum; 

(btw, I am making a project using this for a quiz checking program that is why I need the percentage or decimal)

like image 498
Baruch Avatar asked Oct 21 '11 21:10

Baruch


People also ask

How do I calculate a percentage of 2 numbers?

The percentage difference between two values is calculated by dividing the absolute value of the difference between two numbers by the average of those two numbers. Multiplying the result by 100 will yield the solution in percent, rather than decimal form.

How do you find the percentage of 2 subjects?

To calculate your exam percentage, divide the marks you received by the total score of the exam and multiply by 100. The answer is 96%, indicating that you received 96% of the marks in your session. Divide a number by two to get 50 percent of it. For instance, 32 divided by two equals 16.


2 Answers

If you don't add .0f it will be treated like it is an integer, and an integer division is a lot different from a floating point division indeed :)

float percent = (n * 100.0f) / v; 

If you need an integer out of this you can of course cast the float or the double again in integer.

int percent = (int)((n * 100.0f) / v); 

If you know your n value is less than 21474836 (that is (2 ^ 31 / 100)), you can do all using integer operations.

int percent = (n * 100) / v; 

If you get NaN is because wathever you do you cannot divide for zero of course... it doesn't make sense.

like image 101
Salvatore Previti Avatar answered Sep 21 '22 22:09

Salvatore Previti


Two options:

Do the division after the multiplication:

int n = 25; int v = 100; int percent = n * 100 / v; 

Convert an int to a float before dividing

int n = 25; int v = 100; float percent = n * 100f / v; //Or: //  float percent = (float) n * 100 / v; //  float percent = n * 100 / (float) v; 
like image 24
Eric Avatar answered Sep 21 '22 22:09

Eric