user4657588
user4657588

Reputation:

Convert positive number to a negative number - iOS

I have a simple app with an integer. I want to check the value in the integer and change it from a positive to a negative if it is a positive value. I also want it to check to see if the integer is a negative and then change it to a positive if it is currently a negative. The code below is what I thought of:

int number;

// number gets set.... etc...

// Now do number check.
if (number > 0) {
    number = (0 - number);
}

else if (number < 0) {

    // Since number is negative, lets try to
    // minus minus the number and make it positive.
    number = (0 - number);
}

My question is, is my method correct and more importantly a good way of achieving this functionality? I read that you can use a method called abs() but from what I understand its not safe?

Thanks for your time, Dan.

Upvotes: 4

Views: 10920

Answers (4)

billsea
billsea

Reputation: 71

This appears to be working as well:

-(number)

Upvotes: 1

Bharath Vankireddy
Bharath Vankireddy

Reputation: 932

You can write int myNum *= -1; It will change your num to negative.

Upvotes: -1

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16660

Have look at your code and let's boil it down:

 // Now do number check.
if (number > 0) 
{
  number = (0 - number);
}
else if (number < 0) 
{
  // Since number is negative, lets try to
  // minus minus the number and make it positive.
  number = (0 - number);
}

Obviously the statements inside both if-branches are identically. So you can write:

// Now do number check.
if (number > 0 || number < 0)  // || means logical or
{
  number = (0 - number);
}

If you take into account that -0 is 0, you can remove the whole if:

number = (0 - number);

Additionally you can write, …

number = -number

… too or use a multiplication as intended by the other answers.

Upvotes: 8

Sanjay Mohnani
Sanjay Mohnani

Reputation: 5967

Simply use

int number;

number *= -1;

Upvotes: 4

Related Questions