VB.NET Math.Abs: Absolute Value

Math written on chalkboard

You want to compute the absolute value of a number in the VB.NET programming language. In mathematics, the absolute value of a number is always positive: the numbers -10 and 10 both have the absolute value of 10. In the VB.NET language, the Math.Abs function provides this capability.

This VB article shows the Math.Abs Function. Abs computes absolute numbers.

Example

Note

To start, this program demonstrates how Integer types and also Double types can be used with the Math.Abs function. Please notice how only the negative input numbers have a different absolute value: the values -1000 has an absolute value of 1000 and -100.123 has an absolute value of 100.123.

Program that computes absolute values [VB.NET]

Module Module1
    Sub Main()
	' Absolute values of integers.
	Dim value1 As Integer = -1000
	Dim value2 As Integer = 20
	Dim abs1 As Integer = Math.Abs(value1)
	Dim abs2 As Integer = Math.Abs(value2)

	Console.WriteLine(value1)
	Console.WriteLine(abs1)
	Console.WriteLine(value2)
	Console.WriteLine(abs2)

	' Absolute values of doubles.
	Dim value3 As Double = -100.123
	Dim value4 As Double = 20.2
	Dim abs3 As Double = Math.Abs(value3)
	Dim abs4 As Double = Math.Abs(value4)

	Console.WriteLine(value3)
	Console.WriteLine(abs3)
	Console.WriteLine(value4)
	Console.WriteLine(abs4)
    End Sub
End Module

Output

-1000
1000
20
20
-100.123
100.123
20.2
20.2

Summary

The VB.NET programming language

Computing absolute values of a number is useful in a variety of numeric contexts in the VB.NET programming language; it is useful even in functions that compute hashes. The Math.Abs function from the .NET Framework provides a convenient and heavily tested command to compute the absolute value.

VB.NET Tutorials
.NET