JavaScript - Working With Numeric Values

Applies to TestComplete 15.47, last modified on January 20, 2023

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 both value types.

The integer value can accept zero, positive and negative numbers within the ±1.7976931348623157x10^308 range. Generally the integer number is considered to be in decimal numeration, however the octal or hexadecimal representation is also possible.

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

The integer is treated as octal, if it is prefixed with zero and contains digits from 0 to 7. For instance, 061 is equivalent to decimal 49. The integer is treated as hexadecimal, if it is prefixed with zero followed by the letter "x" (uppercased or lowercased) 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, 0xff is equivalent to decimal 255 and OX5EA is equivalent to decimal 1514.

Floating-point numbers have a fractional part that can be as small as ±5x10^-324. 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 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.

To perform mathematical operations over numbers, JavaScript has its own inherent object Math. The object contains properties and methods that correspond to some frequently used constants and mathematical operations. The table below lists the properties and methods of the Math object. For a detailed description, see the documentation on the Math object on the Mozilla Developer Network website.

Property Description
E Returns the mathematical constant e, the base of natural logarithms. Approximately equal to 2.718.
LN2 Returns the natural logarithm of 2. Approximately equal to 0.693.
LN10 Returns the natural logarithm of 10. Approximately equal to 2.302.
LOG2E Returns the base-2 logarithm of e, Euler's constant. Approximately equal to 1.442.
LOG10E Returns the base-10 logarithm of e, Euler's constant. Approximately equal to 0.434.
PI Returns the ratio of the circumference of a circle to its diameter. Approximately equal to 3.14159.
SQRT1_2 Returns the square root of 0.5. Approximately equal to 0.707.
SQRT2 Returns the square root of 2. Approximately equal to 1.414
Method Description
abs(number) Returns the absolute value of a number.
acos(number) Returns the arccosine of a number.
asin(number) Returns the arcsine of a number.
atan(number) Returns the arctangent of a number.
atan2(y, x) Returns the angle (in radians) from the X axis to a point (y,x).
ceil(number) Returns the smallest integer greater than or equal to its numeric argument.
cos(number) Returns the cosine of a number.
exp(power) Returns e (the base of natural logarithms) raised to the specified power.
floor(number) Returns the greatest integer less than or equal to its numeric argument.
log(number) Returns the natural logarithm of a number.
max([number1[, number2[. . . [, numberN]]]]) Returns the greater of zero or more supplied numeric expressions.
min([number1[, number2[. . . [, numberN]]]]) Returns the lesser of zero or more supplied numeric expressions.
pow(base, power) Returns the value of a base expression taken to a specified power.
random( ) Returns a pseudorandom number between 0 and 1.
round(number) Returns a supplied numeric expression rounded to the nearest integer.
sin(number) Returns the sine of a number.
sqrt(number) Returns the square root of a number.
tan(number) Returns the tangent of a number.

Language-specific operations

JavaScript also has additional arithmetic operations:

Modulo (%) 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.
Increment (++) Requires a single operand. Adds 1 to the operand. If used as a prefix operator (++x), returns the value of its operand after adding 1; if used as a postfix operator (x++), returns the value of its operand before adding 1.
Decrement (--) Requires a single operand. Subtracts 1 from the operand. If used as a prefix operator (--x), returns the value of its operand after subtracting 1; if used as a postfix operator (x++), returns the value of its operand before subtracting 1.
Unary negation (-) Requires a single operand. Returns the inverted value of its operand.

This sample code illustrates how to use them:

JavaScript

function JavaScriptOperators()
{
  let aVar = 7;

  // Modulo
  Log.Message(7%3);    // 1
  Log.Message(6%3);    // 0
  Log.Message(59%10);  // 9
  // Increment
  Log.Message(aVar++); // 7
  Log.Message(aVar);   // 8
  aVar = 7;
  Log.Message(++aVar); // 8
  Log.Message(aVar);   // 8
  // Decrement
  Log.Message(--aVar); // 7
  // Unary negation
  Log.Message(-aVar);  // -7
}

Rounding off

JavaScript has three routines that accept a floating point value and return an integer value, but each of them has its own specific characters. These routines are: floor, ceil and round.

The floor routine always returns the integer value that is smaller than the input value, or in other words it rounds down the input value. It does not distinguish whether the input value is positive or negative. That is, for 0.5 the routine will return 0, and for -0.5 it will return -1.

The ceil routine is similar to floor, but it always returns the integer value that is greater than the input value, or in other words it rounds up the input value. Like the former routine, it does not distinguish whether the input value is positive or negative. For 0.5 the routine will return 1, and for -0.5 it will return 0.

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 to 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 the specifics of rounding with these methods:

JavaScript

function Rounders()
{
    let PositiveFloat1 = 123.456;
    let PositiveFloat2 = 123.567;
    let NegativeFloat1 = -123.456;
    let NegativeFloat2 = -123.567;

    Log.Message("Using the Floor method")
    Log.Message(Math.floor(PositiveFloat1));  // 123
    Log.Message(Math.floor(PositiveFloat2));  // 123
    Log.Message(Math.floor(NegativeFloat1));  // -124
    Log.Message(Math.floor(NegativeFloat2));  // -124

    Log.Message("Using the Ceil method")
    Log.Message(Math.ceil(PositiveFloat1));   // 124
    Log.Message(Math.ceil(PositiveFloat2));   // 124
    Log.Message(Math.ceil(NegativeFloat1));   // -123
    Log.Message(Math.ceil(NegativeFloat2));   // -123

    Log.Message("Using the Round method")
    Log.Message(Math.round(PositiveFloat1));  // 123
    Log.Message(Math.round(PositiveFloat2));  // 124
    Log.Message(Math.round(NegativeFloat1));  // -123
    Log.Message(Math.round(NegativeFloat2));  // -124
}

Division operations

The standard operation of division that is performed by the / operator, generally returns a floating-point result. The returned result (quotient) can be integer only when the first operand (dividend) is evenly divisible by the second operand (divider), or in other words is divided without a remainder (modulo). However, sometimes we need to get an integer quotient for the numbers which are not evenly divisible. Such an operation is called integer division. There are two ways to perform integer division in JavaScript: the first is to calculate a result of a standard division and then round it off to an integer. The second way is to calculate the modulo with the % operator, subtract it from the dividend and then perform the division. Both techniques can be used, but for large number of operations, it is better to use the second one, because it takes less time to run.

The code fragment below gives an implementation for each of the described techniques:

JavaScript

function IntDiv1(a,b)
{
  return Math.round(a/b)
}

function IntDiv2(a,b)
{
  return (a-(a%b))/b
}

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

JavaScript

function NumToStrDemo()
{
  Log.Message(aqConvert.IntToStr(17)); // 17
  Log.Message(aqConvert.IntToStr(0xff)); // 255
  Log.Message(aqConvert.IntToStr(0X47C)); // 1148
  Log.Message(aqConvert.IntToStr(031)); // 25

  Log.Message(aqConvert.FloatToStr(-1234.567890)); // -1234.56789
  Log.Message(aqString.Format("%1.4E", -1234.567890)); // -1.2346E+003
}

Getting numerical values from strings

The aqConvert object has three 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 + 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:

JavaScript

function StrToNumDemo()
{
  let int = aqConvert.StrToInt("-1024");
  Log.Message(int); // -1024

  let floatpt = aqConvert.StrToFloat("-1234.56789e2");
  Log.Message(aqConvert.FloatToStr(floatpt)); // -123456.789
}

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

JavaScript

function ContainsNumber(Str)
{
  let re = /[-+]?\d*\.?\d+([eE][-+]?\d+)?/gm; //Specify the regular expression
  return re.test(Str); //Return the verification result
}

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 hold any number, it is convenient to set the default value that would be returned in this case.

JavaScript

function ExtractNumber(Str, DefaultValue)
{
  let re = /[-+]?\d*\.?\d+([eE][-+]?\d+)?/gm; //Specify the regular expression
  let MatchArr = Str.match(re); //Search for occurrences
  //If no numbers were found then return default value
  if (strictEqual(MatchArr, null)) return DefaultValue
    //Else, convert a string with first occurrence into a number
    else return aqConvert.StrToFloat(MatchArr[0]);
}

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

JavaScript

function NumberFromStr()
{
  let aStr = "A value is : -1.234e2";
  Log.Message(ContainsNumber(aStr)); // True
  Log.Message(ExtractNumber(aStr,-50)); // -123.4
}

See Also

Working With Numeric Values
aqConvert Object

Highlight search results