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
| From | To | With |
|---|---|---|
| text | number | val, valint, vallng, or numeric.TryParse... to reject bad input |
| number | number | assignment, cast( T, x ), cint, cdbl and the other c... functions |
| number | text | str( x ), the & operator, strings.Format |
| your type | another type | a 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
- Change
quantityTextto"12 boxes". What doesvalintmake of it? - Change
priceTextto"seven"and explain the total.