Built-in math functions

Just like other programming languages, VBScript provides a rich library of built-in functions to deal with including strings, dates, typecasting, basic math, etc. When you consider creating functions in any programming language, it is useful to familiarize yourself with the available built-in functions of that language. The idea is if the programming language already provides a built-in function for a specific task, as a programmer, you do not have to create your own function for that task. The built-in function is likely to be more efficient so avoid reinventing-the-wheel!

In this section, we will cover some of the built-in mathematical functions available in VBScript. Most of those functions are very simple to use. Table 1 provides a reference to mathematical functions available in VBScript.

Table 1 Built-in math functions
Built-in math function Meaning
Abs (number) Absolute value
Exp (number) e ^ number; e = 2.71828182845905
Fix (number) Returns integer portion
Int (number) Returns integer portion
Hex (number) Coverts base 10 to hexadecimal
Oct (number) Coverts base 10 to octal
Round (number) Rounds to an integer
Round (number, dec) Rounds to dec decimal places.
Sgn (number) Sign
Sqr(number) (number > 0) Square root

Here is a quick review of some of the built-in math function available in VBScript:

Abs (number) returns the absolute value of a number. In other words, if the number is greater than or equal to zero, the number is returned. If, however, the number is less than zero, the negation of the number is returned. For instance, Abs (5) would return 5 and Abs (-1) would return 1.

Exp (number) raises e (approximately 2.71828) to the power number. For example, Exp (5) says e^5, which is approximately 148.41315.

Fix (number) returns integer portion, greater than or equal to the number. For instance, Fix (-5.80) returns -5.

Int (number) is different from Fix(number) because Int (number) returns integer portion less than or equal to number. For example, Int (-5.80) returns -6.

Hex (number) returns strings consisting of the number converted to hexadecimal base. For example, Hex (10) returns A, Hex (11) returns B, Hex (12) returns C, etc.

Oct (number) returns strings consisting of the number converted to octal base. For instance Oct (8) returns 10, Oct (9) returns 11, Oct (10) returns 12, etc.

Round (number) rounds a number to the nearest integer; for example, Round (5.45) rounds 5.45 to 6 and Round (5.01) returns 5.

Round (number, dec) rounds a number to dec decimal places. Round (5.45, 1) rounds 5.45 to 1 decimal place: 5.4. Round (100.67899, 3) returns 100.679.

Sgn (number) returns -1 if number is less than 0, 0 if number is 0, and 1 if number is greater than 0. Consider the following as examples: Sgn(-5.9) returns -1, Sgn(0) returns 0; and Sgn(5) returns 1.

Sqr (number) (number > 0) provides a square root of number, provided the number is positive. For example, sqr (4) returns 2, sqr (100) returns 10.