9

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

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

But it doesn't work.

Zach Saucier
  • 21,903
  • 12
  • 75
  • 126
user2622574
  • 184
  • 1
  • 2
  • 7

7 Answers7

45
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));
Lake
  • 3,704
  • 24
  • 35
5
int k = (int)(120*50.0/100.0);
Eric Urban
  • 3,365
  • 1
  • 16
  • 22
4

Never use floating point primitive types if you want exact numbers and consistent results, instead use BigDecimal.

The problem with your code is that result of (120/100) is 1, since 120/100=1.2 in reality, but as per java, int/int is always an int. To solve your question for now, cast either value to a float or double and cast result back to int.

2

I suggest using BigDecimal, rather than float or double. Division by 100 is always exact in BigDecimal, but can cause rounding error in float or double.

That means that, for example, using BigDecimal 50% of x plus 30% of x plus 20% of x will always sum to exactly x.

Patricia Shanahan
  • 24,883
  • 2
  • 34
  • 68
1

it is simple as 2 * 2 = 4 :)

int k = (int)(50 * 120) / 100;
Tunaki
  • 116,530
  • 39
  • 281
  • 370
Konstantin F
  • 148
  • 1
  • 12
-1

Division must be float, not int

(120f * 50 / 100f)

Lore Lai
  • 31
  • 4
-1

You don't need floating point in this case you can write

int i = 120 * 50 / 100;

or

int i = 120 / 2;
Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075