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

Conversion

Programs move values between forms all the time: text read from a user or a file becomes a number, numbers of one type meet numbers of another, and results become text again for display. Each of those steps is a conversion, and tiko has a tool for each.

'' A small order: the quantity and price arrive as text.
dim as ustring quantityText = "12"
dim as ustring priceText = "7.29"

'' Text to number: val reads a float64, valint a whole number.
var quantity = valint( quantityText )
var price = val( priceText )

'' Number to number: arithmetic converts to the wider type, and
'' cint converts back to a whole number, rounding.
var total = quantity * price
var wholeTotal = cint( total )
var perItem = cast( float32, total / quantity )

'' Number to text: str, or the & operator.
dim as ustring report = "total " & str( total ) & ", about " & _
                         wholeTotal & ", or " & perItem & " each"
print report
print "the report is"; len( report ); " characters of text"

Output

total 87.48, about 87, or 7.29 each
the report is 35 characters of text
FromToWith
textnumberval, valint, vallng, or numeric.TryParse... to reject bad input
numbernumberassignment, cast( T, x ), cint, cdbl and the other c... functions
numbertextstr( x ), the & operator, strings.Format
your typeanother typea constructor and an operator cast

The example uses one of each. valint and val read the two strings, quantity * price converts the integer to float64 before multiplying, cint rounds the total back to a whole number, and & turns every operand into text as it joins them.

The pages that follow take the steps one at a time: numbers to text, text to numbers, conversions for your own types, and the rules for rounding when a fraction has to go.

Activities

  1. Change quantityText to "12 boxes". What does valint make of it?
  2. Change priceText to "seven" and explain the total.