Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Numbers to Text

print shows a number without being asked, but to keep the text, join it with other text or lay it out in columns, you need the text as a ustring. There are three ways to get it, from the quickest to the most controlled.

#import "std/strings"

dim as int32 count = 42
dim as float64 ratio = 2.71828
dim as boolean ok = true

'' str( x ) is the text of a value, with no leading space.
print "["; str( count ); "] ["; str( -count ); "] ["; str( ratio ); _
      "] ["; str( ok ); "]"

'' & converts each side to text and joins them.
dim as ustring line_ = "count=" & count & ", ratio=" & ratio & ", ok=" & ok
print line_

'' hex, oct and bin show an integer in another base; a second
'' argument pads to that many digits.
print "hex: "; hex( 255 ); " "; hex( 255, 4 ); "  oct: "; oct( 8 ); _
      "  bin: "; bin( 5, 8 )

'' strings.Format controls width, alignment, precision and base.
print strings.Format( "[{:>6}] [{:<6}] [{:06}]", count, count, count )
print strings.Format( "[{:.2f}] [{:.3e}] [{:+}]", ratio, ratio, count )
print strings.Format( "[{:#x}] [{:#b}] [{:>8}]", count, 5, ok )

Output

[42] [-42] [2.71828] [true]
count=42, ratio=2.71828, ok=true
hex: FF 00FF  oct: 10  bin: 00000101
[    42] [42    ] [000042]
[2.72] [2.718e+00] [+42]
[0x2a] [0b101] [    true]

str( x ) gives the text of a number or a boolean. Unlike print, it adds no space in front of a positive number. The & operator calls the same conversion on each side, so "count=" & count needs no str at all.

hex, oct and bin write an integer in base 16, 8 or 2, and an optional second argument pads the result with zeros to that many digits.

strings.Format from std/strings does the rest: width and alignment ({:>6}), zero padding ({:06}), a sign ({:+}), digits after the point ({:.2f}), exponent notation ({:.3e}) and other bases with a prefix ({:#x}). The Formatted print page lists the parts of a format spec.

Activities

  1. Print ratio with 0, 2 and 4 digits after the point.
  2. Print the numbers 1 to 12 in hexadecimal, two digits each, on one line.