Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java percent of number [duplicate]

Tags:

java

Is there any way to calculate (for example) 50% of 120? I tried:

int k = (int)(120 / 100)*50;

But it doesn't work.

like image 746
user2622574 Avatar asked Aug 03 '13 16:08

user2622574


People also ask

How do you find 5 percent of a number in Java?

Percentage = (Obtained score x 100) / Total Score To get these parameters (inputs) from the user, try using the Scanner function in Java.

How do you double a percentage in Java?

The following code sample shows how to format a percentage. Double percent = new Double(0.75); NumberFormat percentFormatter; String percentOut; percentFormatter = NumberFormat.

How do you write percentages in Java?

In Java, the modulus operator is a percent sign, %. The syntax is the same as for other operators: int quotient = 7 / 3; int remainder = 7 % 3; The first operator, integer division, yields 2.

How do you find 10 percent of a number?

​10 percent​ means ​one tenth​. To calculate 10 percent of a number, simply divide it by 10 or move the decimal point one place to the left. For example, 10 percent of 230 is 230 divided by 10, or 23.


1 Answers

int k = (int)(120 / 100)*50;

The above does not work because you are performing an integer division expression (120 / 100) which result is integer 1, and then multiplying that result to 50, giving the final result of 50.

If you want to calculate 50% of 120, use:

int k = (int)(120*(50.0f/100.0f));

more generally:

int k = (int)(value*(percentage/100.0f));
like image 190
Lake Avatar answered Nov 11 '22 18:11

Lake