Valeri Petkov
Valeri Petkov

Reputation: 55

Double not changing its value properly

I am trying to calculate the Net Income based on a given Gross Income Value. The rules are this :

  1. If grossValue is lower or equal to 1000, no tax is applied
  2. 10% Tax is applied to the exess amout

Example : Given a gross value of 3400, we apply 10% tax to the exess so 10% out of 2400 is 240 => Then we just return 2160 + 1000

The problem is this line : double netSalary = exessAmout - (10 / 100 * exessAmout); For some reason the value doesnt change


public double CalculateNetSalary(double grossSalary)
{
    // Taxes dont apply, return grossValue
    if(grossSalary <= 1000)
    {
    return grossSalary;
    }

    double exessAmout = grossSalary - 1000;
    
    // Apply normal tax 
    double netSalary = exessAmout - (10 / 100 * exessAmout);
    
    return netSalary + 1000;
}

I expected given a value of 3400 to receive 3160

Why :

using a calculator to solve this I get the right answer, but running the code the value always stays the same

Upvotes: 0

Views: 55

Answers (2)

Sachith Wickramaarachchi
Sachith Wickramaarachchi

Reputation: 5872

First As mentioned jmcilhinney in his answer you need to make this 10 / 100 for double literals. and you expecting here 3160 as an answer? that expected result is breaking in here.

// Apply Social Tax
if (grossSalary > 3000)
{
    netSalary -= (10.0 / 100.0 * netSalary);
    Console.WriteLine(netSalary);
}

You have applied Social Tax for the netSalary value. 3160. According to it, output should be 2944

Upvotes: 0

jmcilhinney
jmcilhinney

Reputation: 54487

You are doing integer division. When you divide an int by another int then the result will be an int, which means that 10 / 100 will be zero. Make them double literals, i.e. 10.0 / 100.0, and it should work.

Upvotes: 1

Related Questions