Skip to main content

Formatting and Conversion

BBj's STR() function handles both number-to-string conversion and formatted output using masks. NUM() converts the other direction -- string to number. Together they cover the formatting and parsing tasks that other languages need printf, DecimalFormat, or template literals for.

STR() -- Number to String

Basic conversion without formatting:

x = 42.5
print str(x)
rem Output: 42.5

STR() with Numeric Masks

Add a mask after a colon to format the output:

print str(3352.3:"$##,##0.00")
rem Output: $3,352.30

Numeric Mask Characters

CharacterMeaning
#Digit placeholder (suppressed if zero)
0Digit placeholder (shows zero)
.Decimal point
,Thousands separator
$Literal dollar sign
-Minus sign (for negatives)
%Literal percent sign
BInsert blank if result is zero

More examples:

print str(42:"000")
rem Output: 042

print str(0.5:"##0.00%")
rem Output: 0.50%

print str(-15.3:"##0.00-")
rem Output: 15.30-

The mask determines the width and formatting. If the number does not fill all # positions, those positions are blank. If the number is too large for the mask, BBj returns asterisks (*) to indicate overflow.

STR() with String Masks

STR() also reformats strings by mapping characters through a mask. Use X as the character placeholder:

print str("5551234567":"(XXX) XXX-XXXX")
rem Output: (555) 123-4567

print str("123456789":"XXX-XX-XXXX")
rem Output: 123-45-6789

Each X in the mask consumes one character from the input string. All other characters in the mask are inserted literally. This is useful for formatting phone numbers, identifiers, and other fixed-format data.

NUM() -- String to Number

NUM() converts a string to a numeric value:

print num("123.45")
rem Output: 123.45

print num(" 42 ")
rem Output: 42

NUM() handles leading and trailing whitespace automatically.

Error Handling with NUM()

If the string cannot be converted, NUM() raises error 26 (non-numeric data). Use ERR= to handle this:

x = num("abc", err=bad_number)
print x
stop

bad_number:
print "Not a valid number"

See the Error Handling chapter for details on ERR= and other error trapping techniques.

Common Mask Patterns

MaskInputOutputUse Case
$##,##0.003352.3$3,352.30Currency
00042042Zero-padded
##0.0%0.5 0.5%Percentage
(XXX) XXX-XXXX5551234567(555) 123-4567Phone number
XXX-XX-XXXX123456789123-45-6789SSN format
##,##01500 1,500Integer with commas
Reading Legacy Code

See Reading Legacy Code for inline PRINT masks, uppercase keywords, and other historical formatting patterns.

Further Reading