DelphiScript - Working With Numeric Values

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

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

Basics

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 the values of 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 decimal numeration, however the hexadecimal representation is also possible.

The hexadecimal numbers can be negative, but cannot be written in the exponential form or cannot have a fractional part.

The integer is treated as hexadecimal, if it is prefixed with dollar sign ($) and contain 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, $ff is equivalent to decimal 255 and $5EA is equivalent to decimal 1514.

Floating-point numbers have a fractional part. They can range from 5.0 x 10^-324 to 1.7 x 10^308. 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 dealing with numerical values. The tables below list those 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 the 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, DelphiScript has several functions that perform mathematical operations over numbers. Most of them are ported from the original Delphi's System unit. The table below lists these functions.

Function Description
Abs(number) Returns the absolute value of a number.
Cos(number) Returns the cosine of a number.
Dec(number[, IncStep]) Decreases the given number by one or by specified value.
Exp(power) Returns e (the base of natural logarithms) raised to the specified power.
Frac(number) Returns the fractional part of a specified number.
Inc(number[, IncStep]) Increases the given number by one or by specified value.
Int(number) Returns the integer part of a specified number.
Ln(number) Returns the natural logarithm of a number.
Pi Returns the Pi constant, which is approximately equal to 3.1415926535897932385.
Random Returns a pseudorandom number between 0 and 1.
Random(iRange) Returns a pseudorandom number between 0 and iRange-1.
Randomize Initializes the random number generator with a value taken from the current tick count. If Randomize is never called, scripts using Random will always run through the same sequence of "random" numbers. If it is called all the time, they may well get the same number on all calls to Random. Randomize should be called only once, at the start of the main script.
RandSeed Variable. Specifies the initial value for the random number generator. This can be necessary to generate the same sequences of "random" numbers in your scripts.
Round(number) Rounds the specifies to the nearest integer value. If the number is exactly midway between two integers, returns the greater integer of the two.
Sin(number) Returns the sine of a number.
Sqr(number) Returns the squared value of a number.
Sqrt(number) Returns the square root of a number.

Language-specific operations

DelphiScript also has some additional arithmetic operators:

Integer division (div) 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 integer.
Sign identity (+) Requires a single operand. Returns the value of the same sign as the operand.
Sign negation (-) Requires a single operand. Returns the value of the opposite sign than the operand.

This sample code illustrates how to use them:

DelphiScript

procedure DelphiScriptOperators;
var aVar1, aVar2: integer;
begin

  //Integer division
  Log.Message(40 div 10); //Posts 4
  Log.Message(49 div 10); //Posts 4
  //Modulo
  Log.Message(7 mod 3);    //Posts 1
  Log.Message(40 mod 10);  //Posts 0
  Log.Message(49 mod 10);  //Posts 9
  //Sign identity
  aVar1:=7;
  aVar2:=-7;
  Log.Message(+aVar1); //Posts 7
  Log.Message(+aVar2); //Posts -7
  //Sign negation
  Log.Message(-aVar1);  //Posts -7
  Log.Message(-aVar2);  //Posts 7 
end;

Rounding off

DelphiScript has a pair of routines that accept a floating point value and return an integer value. These routines are: Int and Round.

The Int 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 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 is also applied for the 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.

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

DelphiScript

function Rounders;
var PositiveFloat1, PositiveFloat2, NegativeFloat1, NegativeFloat2: real;
begin
    PositiveFloat1:=123.456;
    PositiveFloat2:=123.567;
    NegativeFloat1:=-123.456;
    NegativeFloat2:=-123.567;
    
    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: -123
    Log.Message(Int(NegativeFloat2));  //Result is: -123

    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
end;

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 these purposes, aqConvert has two methods: IntToStr and FloatToStr. You amy also find that the Format method of the aqString object is useful.

IntToStr 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 methods. The FloatToStr is the simplest: the generated string contains up to 15 digits and the decimal separator is only displayed when required. To specify a format of the resulting string use the Format method. It provides the greatest flexibility since it allows you to set a user-defined formatting string.

The code below illustrates how to use these methods.

DelphiScript

procedure NumToStrDemo;
var int: integer;
    floatpt: real;
begin
  int:=17;
  Log.Message(aqConvert.IntToStr(int)); //Posts 17
  int:=$ff;
  Log.Message(aqConvert.IntToStr(int)); //Posts 255
  int:=$047C;
  Log.Message(aqConvert.IntToStr(int)); //Posts 1148
  
  
  floatpt:=-1234.567890;
  Log.Message(aqConvert.FloatToStr(floatpt)); //Posts -1234.56789
  Log.Message(aqString.Format('%1.4E',floatpt)); //Posts -1.2346E+003
end;

Getting numerical values from strings

The aqConvert object has three methods that let you convert a string into a number. They are: StrToInt, StrToInt64 and StrToFloat.

The StrToInt and StrToInt methods accept a string holding a decimal representation of a number and return an integer. The input string can only contain digits and + 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 those methods:

DelphiScript

function StrToNumDemo;
var int: integer;
    floatpt: real;
begin
  int:=aqConvert.StrToInt('-1024');
  Log.Message(int); //Posts -1024
  
  floatpt:=aqConvert.StrToFloat('-1234.56789e2');
  Log.Message(aqConvert.FloatToStr(floatpt)); //Posts -123456.789
end;

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+)?.

Here 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.

DelphiScript

function ContainsNumber(Str);
var
  re: OleVariant;
begin
  re:=HISUtils.RegExpr;
  re.Expression:='[-+]?\d*\.?\d+([eE][-+]?\d+)?';  //Specify the regular expression
  Result:=re.Exec(Str)  //Return the verification result
end;

The same regular expression can be used to extract the 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 have a number, it is convenient to set the default value that would be returned in this case.

DelphiScript

function ExtractNumber(Str, DefaultValue);
var
  re: OleVariant;
begin
  re:=HISUtils.RegExpr;
  re.Expression:='[-+]?\d*\.?\d+([eE][-+]?\d+)?';  //Specify the regular expression
  //Search for occurrences
  //If no numbers were found then return default value
  if (not re.Exec(Str))then Result:=DefaultValue
                 //Else, convert a string with first occurrence into a number
                 else Result:=aqConvert.StrToFloat(re.Match[0]);
end;

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

DelphiScript

procedure NumberFromStr;
var aStr: string;
begin
  aStr:='A value is : -1.234e2';
  Log.Message(ContainsNumber(aStr)); //Posts True
  Log.Message(ExtractNumber(aStr,-50)); //Posts -123.4
end

See Also

Working With Numeric Values
aqConvert Object

Highlight search results