View Full Version : string to number conversion
sandyrepope
23-02-2007, 18:06
I've been all through the help and can't seem to figure this out.
How do I take a string (example: "123") and convert it to a number (example: 123)?
I suspect that it has something to do with CVx commands but I just don't understand if this is right or not.
Thanks
ErosOlmi
23-02-2007, 18:36
Sandy,
thinBasic automatically make conversions for you based on target variable type.
For example:
DIM MyLong AS LONG
'---Because target variable is numeric, all tokens after equal sign will be automatically converted to numeric
MyLong = "123"
MsgBox 0, MyLong
is something strange in many standard languages but not in thinBasic.
Also true, the other way round, assigning a number to a string
DIM MyString AS STRING
'---Because target variable is string, all tokens after equal sign will be automatically converted to string
MyString = 123
MsgBox 0, MyString
Of course thinBasic has also the standard BASIC functions (present in almost any BASIC language) to convert from number to string and from string to number.
They are the following:
from number to string use STR$ (http://www.thinbasic.com/public/products/thinBasic/help/html/str$.htm)(AnyNumericExpression)
from string to number use VAL (http://www.thinbasic.com/public/products/thinBasic/help/html/val.htm)(AnyStringExpression)
CV* and MK* equivalent functions are other beasts and they are used for binary manipulation or memory handling. So better to forget about it for the moment.
Ciao
Eros
ErosOlmi
23-02-2007, 19:31
Do not forget also FORMAT$ (http://www.thinbasic.com/public/products/thinBasic/help/html/format$.htm)
Very nice when you need to convert from number to string and at the same time format numeric output.
Examples:
'---Define a string
DIM MyString AS string
'---All valid formatting
MyString = fORMAT$(0.75, "*=##.###")
MyString = FORMAT$(1 / 5, "0.0%")
MyString = FORMAT$(1212.46, "$00,000.00")
MyString = FORMAT$(123,"$*=###0,.00#")
MyString = FORMAT$(5.55, """XYZ=""#.##\#")
'---Test latest
MsgBox 0, MyString
Ciao
Eros
sandyrepope
23-02-2007, 22:35
Most of this information I didn't know. I, also, can't understand how I overlooked VAL. This info will sure come in handy for all beginners like myself.
Thanks