-8

What is the best way to switch between a positive and negative value in a statement (in the example of a boolean):

myBoo = !myBoo

To do the same with an int I would need to check with if statement:

if (val >= 0)
{
     val = val*-1
}
else
{
    val = Math.abs(val);
}

is there a more direct way to do this?

Thanks in advance

The Impaler
  • 45,731
  • 9
  • 39
  • 76
neulass
  • 13
  • 1

4 Answers4

8
int myBoo = 7;

myBoo = -myBoo;
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • 2
    More efficient than multiplication afaik, so +1. – Perry Monschau Jul 23 '18 at 16:04
  • @PerryMonschau I think in practice that this wouldn't be more efficient, at least measurably so, an interesting benchmark to try out though. – DavidG Jul 23 '18 at 16:22
  • @DavidG I think this sort of benchmark would come down to the compiler used. Probably most are smart enough to compile both into the same operation, if I'm not mistaken. – Perry Monschau Jul 23 '18 at 16:25
  • @PerryMonschau Well I doubt they would compile to the same operation, at least not in C#. I just don't think the difference would be much, if anything. – DavidG Jul 23 '18 at 16:38
  • @DavidG Different code for different situations. If this operation takes place in the core process of an application and wants to run a million times a second, then every optimisation counts. – Perry Monschau Jul 23 '18 at 16:52
  • @PerryMonschau Yes, but I'm suggesting that even that won't matter. – DavidG Jul 23 '18 at 16:53
  • @DavidG like you said, an interesting benchmark to try out. – Perry Monschau Jul 23 '18 at 16:53
  • 2
    @PerryMonschau Well I tried it with 100 million iterations and that gave me a difference of 0.1s in total, second run it was the other way round. So not enough for most mortals to worry about :) – DavidG Jul 23 '18 at 17:03
0

there is a function: Math.negateExact. https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#negateExact-int-

Hemant Singh
  • 1,487
  • 10
  • 15
0

One way would be to just add a negative sign in front of the value:

int myInt = -myInt; 

Another way to switch between a positive or negative number in a statement would be to multiply it by -1.

myInt = myInt * -1;
Fuzzybear
  • 1,388
  • 2
  • 25
  • 42
-2

You can use Math.signum(), it returns -1.0 if number is negative and 1.0 if it is positive, 0 if it is zero

  • The person asking the question wants to negate the number. so for example given `1234` it would give you `-1234`. This does not answer the question at all. – DavidG Jul 23 '18 at 16:23