Johnathan
Johnathan

Reputation: 134

How do I prevent an int from becoming negative after subtracting

I am trying to subtract a value from an int which has a set value. Once it gets to 0 and I subtract more from it, the value becomes negative.

I thought if I used an if-else statement to check whether the value goes below 0 it would prevent the value from becoming negative. But the value proceeds into the negative. How do I prevent the value from going into the negative range?

        {
            DateTime start = dateTimePicker2.Value.Date;
            DateTime end = dateTimePicker1.Value.Date;

            TimeSpan difference = end - start;

            int days = difference.Days;
            int min = 0;
            int max = 21;
            int rdays = Convert.ToInt32(Holidays_Number_lbl.Text);
            Holidays_Number_lbl.Text = (rdays - days).ToString();

            int Holidays_Number = int.Parse(Holidays_Number_lbl.Text);
            if ((Holidays_Number > min)  && (Holidays_Number < max))
            {
                MessageBox.Show("Holidays have been counted");
            }
            else
            {
                MessageBox.Show(" You have exceeded your 21 holidays  ");//value goes into the minus ?
            }
        }

Expected result: MessageBox appears saying you have exceeded your days and value doesn't go into the negative.

Actual Result: Value proceeds into the negative.

Upvotes: 1

Views: 3126

Answers (2)

Douglas Reid
Douglas Reid

Reputation: 3788

You can specify zero as the lowest possible value with Math.Max()on the line where you do the arithmetic:

Holidays_Number_lbl.Text = (Math.Max(rdays - days, 0)).ToString();

However, you're converting to a string and then back to a number. Something like this would eliminate the need for int.Parse:

...

 int Holidays_Number = Math.Max(rdays - days, 0);
 Holidays_Number_lbl.Text = Holidays_Number.ToString();
 if ((Holidays_Number > min)  && (Holidays_Number < max))
 {

...

Upvotes: 3

Tim
Tim

Reputation: 2098

This line int Holidays_Number = int.Parse(Holidays_Number_lbl.Text); is setting the value of Holidays_Number. Then the next line checks that with an if statement. But the if statement does not change the value, it just checks it. So if it is below 0, it will remain below 0.

Upvotes: 1

Related Questions