0

Question

I have example of salary = 2000 and I want to increase the salary by a bonus of 50%, resulting in a salary of 3000.

So like:

salary = salary + 50% of the salary

Attempt

I tried implementing it like this:

int salary = 2000;
salary = salary + 50 % salary;

System.out.println(salary);

but I got 2050 as result, not 3000. What am I doing wrong?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Zervis _
  • 11
  • 5
  • 5
    `%` does not mean "percent" in Java, or most other programming languages. – Fred Larson Sep 28 '21 at 14:40
  • 1
    Think about it this way: 50% is "half" and "half" could be expressed as 0.5. So "add 50% of salary means something like `salary = salary + 0.5 * salary`, `salary += 0.5 * salary` or `salary *= 1.5` (you might need to cast to `int` though). – Thomas Sep 28 '21 at 14:42
  • 1
    use `salary = (int) (1.5 * salary);`. – Socowi Sep 28 '21 at 14:43
  • 1
    I think what you are trying to do is multiply by 1.5 – Kris Sep 28 '21 at 14:44
  • 1
    `salary = 3 * salary / 2;` or `salary += salary / 2;`, if you want to do it all in integer arithmetic. – Andy Turner Sep 28 '21 at 14:45
  • salary *= 1.5 will do the trick. A general way would be salary *= (1.0 + fraction) – duffymo Sep 28 '21 at 17:16

3 Answers3

3

You'd multiply

int salary = 2000;  
salary = (int) (1.5 * salary);

Note that this is only correct for even integers.

You shouldn't use ints, floats, or doubles for currency types

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I would avoid casting the value to `int`. That would mean that the value would be rounded and that might not be what is intended. – João Dias Sep 28 '21 at 14:48
  • 2
    @JoãoDias how are you going to do it without rounding, given that `salary` is an int? – Andy Turner Sep 28 '21 at 14:48
  • If a non-decimal value is mandatory of course we would need to round it, but I don't see anything in the question stating that a non-decimal value is intended. – João Dias Sep 28 '21 at 14:50
  • 1
    Lets ask OP and wait for a clarification. Until then, having both answers seems to be a good compromise, I think. @JoãoDias – Zabuzard Sep 28 '21 at 14:51
  • 3
    Why not use `int` for currency, other than you'd want it to represent cents rather than dollars (or whatever local currency is), and range could be an issue? – Fred Larson Sep 28 '21 at 14:52
1

Try the following:

int salary = 2000;
double finalSalary = salary + 0.5*salary;
System.out.println(finalSalary);

or

int salary = 2000;
double finalSalary = salary * 1.5;
System.out.println(finalSalary);
João Dias
  • 16,277
  • 6
  • 33
  • 45
1

50 % salary

means "the remainder of dividing 50 by salary", because % is the remainder operator. Since 50 < salary, the value of that expression is just 50.

50% of salary is given by salary / 2. So you can write:

salary = salary + (salary / 2);
// or
salary += salary / 2;
// or
salary = salary * 3 / 2;
// etc.
Andy Turner
  • 137,514
  • 11
  • 162
  • 243