Issue
- Using addition in a JavaScript, but it is performing a string concatenation.
Example:
The value in the database is 3.
value = value + 1;
The resulting value is 31, not 4. - Comparisons are returning unexpected results
- NaN (Not a Number) resulting from a JavaScript function
Product Line
TAC Vista
Environment
- TGML
- JavaScript
- Vista 5 Graphics
Cause
Values that are read into a JavaScript in a TGML graphic need to be cast to the correct data type. Some values may be read in as an ASCII string, and this can cause unexpected results.
Resolution
Cast the value being read to the desired data type. There are three options for casting values to numerical values that can then be used in mathematical operations. In the example below a variable named "value" reads a database value from a binding. No type casting is performed, so this value may be interpreted as an ASCII string.
function OnSignalChange(evt){ value = evt.getValue(); }
To ensure that the data are represented as numerical value, select one of the three options below. Replace the variable declaration (highlighted) with one that utilizes the appropriate type casting.
- Number()
value = Number(evt.getValue());
The Number() function will treat the whole object as a number. Non-numerical characters will return NaN. - parseInt()
value = parseInt(evt.getValue());
The parseInt() function will convert the beginning of a string to an Integer value, ignoring any decimal points or any trailing non-numbers. - parseFloat()
value = parseFloat(evt.getValue());
The parseFloat() function will convert the beginning of a string to a floating point decimal value, ignoring any trailing non-numbers.
Also check out the JavaScript Essentials - Episode 3 - Value Types Quick-Help video on the Exchange.