VBScript - Working With Numeric Values

Applies to TestComplete 15.63, last modified on April 10, 2024

This topic contains information about handling numeric data type values and provides examples in the following sections:


The numeric values can be of integer and floating-point type and the TestComplete scripting engine does not distinguish floating-point and integer data types, so the same variable can hold values from both types.

The integer value can accept zero, positive and negative numbers within the ±2147483647 range. Generally, the integer number is considered to be in the decimal format, however octal and hexadecimal representation is also possible.

The octal and hexadecimal numbers can be negative, but cannot be written in the exponential form or cannot have fractional parts.

The integer is treated as octal, if it is prefixed with "&O" and contains digits from 0 to 7. For instance, &O61 is equivalent to decimal 49. The integer is treated as hexadecimal, if it is prefixed with "&H" and contains digits from 0 to 9 or letters from A to F (uppercased or lowercased). The letters from A to F are used to represent numbers from 10 to 15. For instance, &Hff is equivalent to decimal 255 and &H5EA is equivalent to decimal 1514.

Floating-point numbers have a fractional part that can be as small as ±1.401298^-45. The floating-point number can be within the ±3.402823^38 range. Generally, the fractional part is separated by the decimal point character. For example, 123.456. Another possible notation for the floating point value is scientific or exponential notation. In this notation the exponent symbol "e" means "ten to the power of". For example, 37e2 is a scientific notation for 3700.

The aqConvert and aqString objects contain several methods that can be helpful when working with numeric values. The tables below list these methods. The objects are available for all supported scripting languages, so that you can use them to operate with date values regardless of the chosen language.

Method Description
FloatToStr Converts a floating-point value to a string.
Format Converts a floating-point value to a string using the one of predefined format settings.
IntToStr Converts the given number into a string.
StrToFloat Converts the specified string to a floating-point value.
StrToInt Converts the specified string to an integer value.
StrToInt64 Converts the specified string to a long integer value.

Furthermore, VBScript has several functions that perform mathematical operations over numbers. The table below lists these functions. For a more detailed description, see the Math Fuctions article in the MSDN library.

Function Description
Abs(number) Returns the absolute value of a number.
Atn(number) Returns the arctangent of a number.
Cos(number) Returns the cosine of a number.
Exp(power) Returns e (the base of natural logarithms) raised to the specified power.
Fix(number) Truncates the input value by excluding the fractional part.
Int(number) Returns the integer part of a specified number. If the number is negative it is rounded down.
Rnd([number]) Returns a pseudorandom number between 0 and 1. The parameter value determines how Rnd generates a random number: if it is negative, then the same number is generated each time; if it is zero, then the recently generated number is returned; if it is not specified or is positive, then a new random number is generated.
Round(number[, numdecimalplaces]) Returns a number rounded to a specified number of decimal places. If second parameter is omitted rounds off to integer.
Sgn(number) Returns an integer indicating the sign of a number.
Sin(number) Returns the sine of a number.
Sqr(number) Returns the square root of a number.
Tan(number) Returns the tangent of a number.

Language-specific operations

VBScript also has additional arithmetic operators, they are listed in the table:

Exponentiation (^) Raises a number to the power of an exponent.
Integer division (\) Calculates the integer result of division for the numbers which are not evenly divisible.
Modulo (Mod) Calculates the remainder of the division and is only concerned with the resulting remainder after division is performed on two operands. If the operands are floating point numbers, then they are rounded to an integer.
Sign negation (-) Requires a single operand. Returns the value of the opposite operand sign.

This sample code illustrates their use:


Sub VBScriptOperators
  Log.Message(10^2)    'Posts 100
  'Integer division
  Log.Message(40 \ 10) 'Posts 4
  Log.Message(49 \ 10) 'Posts 4
  Log.Message(7 Mod 3)    'Posts 1
  Log.Message(40 Mod 10)  'Posts 0
  Log.Message(49 Mod 10)  'Posts 9
  'Sign negation
  Log.Message(-aVar1)  'Posts -7
  Log.Message(-aVar2)  'Posts 7 
End Sub

Rounding off

VBScript has several functions that accept a floating point value and return an integer value. These routines are: Fix, Int and Round.

The Fix routine truncates the specified value. The returned value is equal or smaller than the positive input value, and equal or greater than the negative input value. That is, for 1.5 the routine will return 1, and for -1.5 it will return -1.

The Int routine is similar to Fix, but for negative input values it returns the integer value that is smaller than the input value, or in other words it rounds down the input value. For 1.5 the routine will return 1, and for -1.5 it will return -2.

The Round routine implements the most common method of rounding, that is also known as symmetric arithmetic rounding. It returns the nearest integer that corresponds to the given floating-point value. If the fractional part of an input value is equal to or greater than 0.5, then the resulting integer is greater than the input value, otherwise - the result is less than the input value. This rule applies to positive numbers, the same rule also applies for negative numbers, but with one difference - the absolute values are used instead of actual input values. That is, for 0.4 the routine will return 0, for 0.5 it will return 1, and for -0.5 it will return -1.

Furthermore, you can use this function to round floating-point values to a specified precision. With the second parameter you can set how many places to the right of the decimal separator are included in the rounding. For example, the Round (3.6297, 2) will result in 3.63.

Here is a sample code that demonstrates how to use those functions:


Sub Rounders
    Log.Message("Using the Fix function")
    Log.Message(Fix(PositiveFloat1))  'Result is: 123
    Log.Message(Fix(PositiveFloat2))  'Result is: 123
    Log.Message(Fix(NegativeFloat1))  'Result is: -123
    Log.Message(Fix(NegativeFloat2))  'Result is: -123
    Log.Message("Using the Int function")
    Log.Message(Int(PositiveFloat1))  'Result is: 123
    Log.Message(Int(PositiveFloat2))  'Result is: 123
    Log.Message(Int(NegativeFloat1))  'Result is: -124
    Log.Message(Int(NegativeFloat2))  'Result is: -124

    Log.Message("Using the Round function")
    Log.Message(Round(PositiveFloat1))  'Result is: 123
    Log.Message(Round(PositiveFloat2))  'Result is: 124
    Log.Message(Round(NegativeFloat1))  'Result is: -123
    Log.Message(Round(NegativeFloat2))  'Result is: -124
    Log.Message(Round (3.6297, 2))      'Result is: 3.63
    Log.Message(Round (-3.6217, 2))     'Result is: -3.62
End Sub

Converting to strings

One of the most frequent actions over numbers is converting them to strings. This could be required to post a numerical value to the TestComplete log, output the test result, write data to a text file and in many other situations. For this purpose, aqConvert has two methods: IntToStr and FloatToStr. You can also find the Format method of the aqString object useful.

The IntToStr method accepts an integer value and returns a string holding its decimal representation. The integer values can be in decimal, octal or hexadecimal form, but the resulting string is always in the decimal form.

To convert floating-point numbers, use the FloatToStr or Format method. The FloatToStr is the simplest: the generated string contains up to 15 digits and the decimal separator is only displayed when required. To specify the format of the resulting string, use the Format method. It provides great flexibility, since it allows you to set a user-defined formatting string.

The code below illustrates how to use these methods.


Sub NumToStrDemo
  Log.Message(aqConvert.IntToStr(intV)) 'Posts 17
  Log.Message(aqConvert.IntToStr(intV)) 'Posts 255
  Log.Message(aqConvert.IntToStr(intV)) 'Posts 1148
  Log.Message(aqConvert.IntToStr(intV)) 'Posts 25
  Log.Message(aqConvert.FloatToStr(floatpt)) 'Posts -1234.56789
  Log.Message(aqString.Format("%1.4E",floatpt)) 'Posts -1.2346E+003
End Sub

Getting numerical values from strings

The aqConvert object has two methods that convert a number out of a string. They are StrToInt, StrToInt64 and StrToFloat.

The StrToInt and StrToInt64 methods accept a string holding a decimal representation of a number and return an integer. The input string can only contain digits and the + or - sign. All other symbols are not allowed. If the input string does not hold a valid integer an exception occurs.

To get a floating-point number from a string use the StrToFloat method - it accepts a string that consists of digits, decimal separator, "+" or "-" symbols and mantissa ("e" or "E" character followed by a positive or negative integer) and returns the floating-point number. If the input string does not hold a floating-point number an exception occurs.

Here is a sample that shows how to use these methods:


Sub StrToNumDemo
  Log.Message(intV) 'Posts -1024
  Log.Message(aqConvert.FloatToStr(floatpt)) 'Posts -123456.789
End Sub

However, sometimes, the functionality of these methods is insufficient, since they have some drawbacks when working with arbitrary strings. StrToInt, StrToInt64 and StrToFloat methods cannot recognize strings containing characters other than those mentioned above. If these methods cannot recognize the string, they raise an exception.

A versatile routine that would extract numbers from any textual string and recognize both integer and floating point values can be implemented with the help of regular expressions. The following regular expression pattern would match positive or negative integer numbers, as well as floating-point numbers both in general and scientific notations: [-+]?\d*\.?\d+([eE][-+]?\d+)?.

Below is a sample for a routine that verifies whether a string contains a number. It uses the regular expression to check the input string and returns True if the input string holds an integer or floating point number.


Function ContainsNumber(Str)
Dim re
  Set re = New RegExp
  re.Pattern = "[-+]?\d*\.?\d+([eE][-+]?\d+)?" 'Specify the regular expression
  re.IgnoreCase = True   ' Set case insensitivity.
  re.Global = True       ' Set global applicability.

ContainsNumber=re.Test(Str)      'Return the verification result
End Function

The same regular expression can be used to extract a number from a string. Since the input string can contain more than one number matching the regular expression, only the first occurrence would be returned by the routine. If the string does not hold any number, it is convenient to set the default value that would be returned in this case.


Function ExtractNumber(Str, DefaultValue)
Dim Matches, re
  Set re = New RegExp
  re.Pattern = "[-+]?\d*\.?\d+([eE][-+]?\d+)?" 'Specify the regular expression
  re.IgnoreCase = True   ' Set case insensitivity.
  re.Global = True       ' Set global applicability.
  Set Matches = re.Execute(Str) 'Search for occurrences
  'If no numbers were found then return default value
  If Not re.Test(Str) Then 
        'Else, convert a string with first occurrence into a number
        Else ExtractNumber=aqConvert.StrToFloat(Matches(0).Value)
  End If
End Function

Here is an example of how to use these two routines:


Sub NumberFromStr
  aStr="A value is : -1.234e2"
  Log.Message(ContainsNumber(aStr))    'Posts True
  Log.Message(ExtractNumber(aStr,-50)) 'Posts -123.4
End Sub

See Also

Working With Numeric Values
aqConvert Object

Highlight search results