Commodore‎ > ‎BASIC‎ > ‎Keywords‎ > ‎

STR$

Keyword Abbreviation Token (hex) Version(s) Classification
STR$ ST{Shift+R} C4 1.0+ Function

  Syntax  
STR$ number )
 
Parameters Type Legal Value(s) Default Value Note(s)
number Floating-point or Integer
any
 
Returns Type Value(s) Note(s)
decString String
sign character, 1 to 9 digits, possible exponent
positive numbers have a space for the sign character
if ABS(number) >= 1.0e9 or less than .01, scientific format is generated
 
 
  Purpose  
Return a string containing a decimal represention of the given number.

 
  Remarks  
The STR$ function generates a (normal, decimal) string representation of a given number, much like you would get with PRINT.  Unlike the similar HEX$ function, this one will accept any number.  The first character will be a space if the number is zero or positive; a minus/hyphen if negative.  Up to nine digits may follow.  If the number is a mathematical integer (not neccessarily a BASIC integer-type) no decimal point or fraction will be generated.  If the number is smaller than 1/100 (0.01) or larger than or equal to 1 billion (1.0e9), then scientific notion will used (i.e., a trailing E, a + or -, and 2-digit exponent).
 
Because BASIC will automatically translate numeric values into a string when using CMD, PRINT, or PRINT#, there is seldom reason to use this, unless you want to process the actual characters that make up the string representation of the number.  (Such as remove the leading space of positive numbers.)  Even in those cases, the USING clause to PRINT / PRINT# is often easier to use (if available in your version of BASIC).  STR$ is handy when a BASIC command/function/statement does not allow a parameter to be numeric, with CHAR being a good example, or when building a string to be sent to a device (typically a command or perhaps some file data).
 
TYPE MISMATCH ERROR is generated with a string expression or variable given for the number (the DEC function may help).  If number is omitted or an invalid expression, SYNTAX ERROR occurs.
 
Because the first character will be a space if the number is non-negative, you may want to remove it.  Here is one way to remove it (it will cut-off the sign if negative):
 MID$(STR$(number),2)
  
Here is a slightly more complex version, but it will not cut-off the sign of a negative number:
 MID$(STR$(number), 2+(number<0) )
 
One important difference from the way STR$ generates a string representation of a number, as compared to the way PRINT and PRINT# work is that there is no trailing "space".  For example, PRINT 7;"X" would generate " 7 X", but PRINT STR$(7);"X" would generate " 7X".
 
Examples:
PRINT STR$("65")

?TYPE MISMATCH ERROR 
READY.
PRINT STR$(65)
 65

READY.
PRINT STR$(0.9)
 .9

READY.
PRINT STR$(0.009)
 9E-03

READY.
PRINT STR$(1.5E8)
 150000000

READY.
PRINT STR$(1.5E9)
 1.5E+09

READY.
  
  Compare With  
 
  Contrast With  
ASC, DECINSTRVAL 
 
  See Also  

© H2Obsession, 2014
Comments