QB64.com

QB64 is a modern extended BASIC programming language that retains QBasic/QuickBASIC 4.5 compatibility and compiles native binaries for Windows, Linux, and macOS.

The VAL Function returns the decimal numerical equivalent value of a STRING numerical value.

Syntax

value = VAL(string_value$)

Description

Example(s)

Differences in values returned with QBasic and QB64:


PRINT VAL("&H") '203 in QB, 0 in QB64
PRINT VAL("&HFFFF") ' -1 QB, 65535 in QB64
PRINT VAL("&HFFFF&") '65535 in both 

Explanation: A quirk in QBasic returned VAL values of 203 for “&” and “&H” that was never fixed until PDS(7.1).

Converting a string with some number characters


 text$ = "1.23Hello"
 number! = VAL(text$)
 PRINT number! 


1.23

Converting literal and variable STRING values to numerical values.


a$ = "33"
PRINT VAL("10") + VAL(a$) + 1 


44

Explanation: 10 + 33 + 1 = 44, the strings were converted to values.

You have to convert the string to values in order to use them in a mathematical expression also since mixing strings with numbers isn’t allowed. VAL will stop at a text letter so VAL(“123G56) would return 123.

If VAL wasn’t used the program would break with an error, as you can’t add the value 1 to a string, if the 1 was a string (“1”) then the program would return “10331”, but now since we used VAL, the numbers were added as they should.

Converting a hexadecimal value to decimal value using HEX$ with VAL.


decnumber% = 96
hexnumber$ = "&H" + HEX$(decnumber%)  'convert decimal value to hex and add hex prefix
PRINT hexnumber$
decimal% = VAL(hexnumber$)
PRINT decimal% 


&H60
 96

Explanation: HEX$ converts a decimal number to hexadecimal, but VAL will only recognize it as a valid value with the “&H” prefix. Especially since hexadecimal numbers can use “A” through “F” in them. Create a converter function from this code!

See Also