views:

539

answers:

4

How do you get the absolute value of a number in vb.net?

Is there a function built in? I know I can simply code a function myself, but I want to know if there is one already there first. It seems so simple, I could probably make it in three lines, so I would be surprised if there isnt one....

Thanks!

+1  A: 

Use Math.Abs.

Vinay Sajip
+1  A: 

The function is Math.Abs

Jason Irwin
+5  A: 

Math.Abs( val )

MSDN Link

Alex Papadimoulis
Thats easy, thanks!
Cyclone
Well, at least the MSDN link has sub-links that mention the potential overflow problem, even if no one would ever think to actually click on them.
MusiGenesis
By the way, I think you should be granted an immediate 20K reputation bonus for your work on The Daily WTF.
MusiGenesis
+2  A: 

At the risk of being down-voted, you may want to write your own absolute value method, depending on what you're using it for. The following code snippet (sorry it's in C#, but the same principle applies):

short i = -32768;
int iAbs = Math.Abs(i);

will happily compile, but when run, the second line will throw an OverflowException with the helpful message "Negating the minimum value of a twos complement number is invalid." In this case, because i is type short, the compiler chooses the overload of Math.Abs that accepts a short and returns a short, and +32768 is not a valid short, so the method throws the exception even if you thought you were anticipating this problem by making iAbs an int.

This snippet:

short i = -32768;
int iAbs = Math.Abs((int)i);

will compile and execute without an exception, but it's kind of clunky to code this way. In my opinion, this is a very sneaky error because it's so rarely encountered in the real world (since there's only one value for each type that will generate this exception). I, unfortunately, run into this error whenever I use Math.Abs for normalizing audio data (which is usually a short[] array), so I've gotten in the habit of writing my own wrapper around Math.Abs that handles all of this for me and just returns a double:

public double AbsThatDoesntSuck(short value)
{
    return Math.Abs((double)value);
}

with overloads for whatever other type I need to handle. I kind of understand why Math.Abs was written to behave this way, but it can definitely bite the behinds of the unaware.

MusiGenesis
Lol, okay, thanks! I can just do a check if the number is less than zero and if it is then multiply it by negative one, which will always work unless the number is too large for Windows to parse.
Cyclone
+1. Absolutely no risk of being downvoted!
RobS