STR$()

Added February 2019

The STR$(x) function, the logical inverse of the VAL(a$) function, returns the string decimal representation of the value (or expression) x, with no leading or trailing blanks. Typically the function is superfluous, since the compiler will automatically insert it whenever it detects the need to convert a numeric value or expression to a string.

Note that when explicitly applied to an expression rather than just a variable or literal, it causes the compiler to expect the expression to be numeric—since the point of the STR$(x) function is to convert the numeric x to string. This can have counter-intuitive side effects, including converting any string operands within the expression to number, and treating the "+" operator as addition rather than concatenation. For example:

map1 a$,s,10

map1 b,f,6,2

map1 c,f,6,3

 

a$ = b + c               ! = 23 

a$ = str$(b) + str$(c)   ! = 23

a$ = str$(b + c)         ! = 5

a$ = str$(a$ + b)        ! = 7

a$ = strexpr$(b + c)     ! = 23

 

The first two statements are equivalent, i.e. the compiler effectively converts the first expression into the second. The reasoning is that since the target of the assignment is a string (a$), the expression on the right side of the equals sign should be a string expression. When the compiler encounters the numeric variables b and c, it therefore inserts implicit str$() functions to convert them to string, and interprets the plus operator as concatenation, i.e. str$(2) + str$(3) = "2" + "3" = "23"

In the third statement, the explicit str$() enclosing the expression causes the compiler to expect the expression to be numeric, which causes it to interpret the plus operator as addition, i.e. 2 + 3 = 5; str$("5") = 5.

The fourth statement is just like the third, except that when the compiler sees the a$ operand within str$(a$ + b), it perhaps counter-intuitively converts it to a number, since it expects the argument of the str$() function to be numeric. So even though we have an explicit str$() function, and a string argument a$, we still treat the plus operator as addition rather than concatenation.

The final statement illustrates the strexpr$() alternative to the str$() function. Added in 6.5 (compiler 890), it tells the compiler to expect a string expression, which in turn causes it to convert the operands b and c to string, and to treat the plus operator as concatenation, which is probably a more intuitive approach when dealing with expressions rather than simple values.

See Also

•   Overloaded Plus Operator

•   STREXPR$()