December 04, 2020, 11:13:28 AM

### Author Topic: [bb] A flexable VAL() Function by Oldefoxx [ 1+ years ago ]  (Read 476 times)

#### BlitzBot

• Jr. Member
• Posts: 1
##### [bb] A flexable VAL() Function by Oldefoxx [ 1+ years ago ]
« on: June 29, 2017, 12:28:38 AM »
Title : A flexable VAL() Function
Author : Oldefoxx
Posted : 1+ years ago

Description : As with the previous submission, but corrected an
oversight where I started to rename the negative
flag to sign, and got interrupted before carrying
through.

Code :
Code: BlitzBasic
1. AppTitle "Emulating a VA() Function
2. ;  by Donald R. Darden, 2001
3. ;  The main program generates sample strings of
4. ;  digits and shows what happens when you convert
5. ;  these values to a float value.
6.
7. While Not KeyHit(1)
8.  sample\$=""
9.  For a=1 To 5
10.    sample\$=sample\$+Chr\$(Rand(48,57))
11.  Next
12.  If Rnd(0,1) And Len(sample)>3 Then
13.    sample\$=Left\$(sample\$,Len(sample\$)-2)+"."+Right\$(sample\$,2)
14.  EndIf
15.  Print Chr\$(34)+sample\$+Chr\$(34)+" = "+val#(sample\$)
16.  WaitKey
17. Wend
18. End
19.
20. Function val#(sstring\$)
21. Local temp#=0
22. Local decimal=0
23. Local sign=1
24. Local a
25. Local b
26. Local c
27. Local base=10
28. a=Instr(sstring\$,"-",1)
29. If a Then negative=-1
30. b=Instr(sstring\$,"&",a+1)
31. If b Then
32.  Select Mid\$(sstring\$,a+1,1)
33.  Case "B", "b"
34.    base=2
35.    a=b+1
36.  Case "O", "o"
37.    base=8
38.    a=b+1
39.  Case "H", "h"
40.    base=16
41.    a=b+1
42.  Default
43.    base=10
44.  End Select
45. End If
46. decimal=0
47. For b=a+1 To Len(sstring\$)
48.  c=Asc(Mid(sstring\$,b,1))
49.  Select c
50.  Case 44          ;","
51.    Goto skip
52.  Case 45          ;"-"
53.    sign=-sign
54.  Case 46          ;"."
55.    decimal=1
56.  Case 48,49,50,51,52,53,54,55,56,57   ;"0" To "9"
57.    temp#=temp*base+c-48
58.    If decimal Then decimal=decimal*base
59.  Case 65,66,67,68,69,60    ;"A" to "F"
60.    If base=16 Then
61.      temp#=temp#*base+c-55
62.      If decimal Then decimal=decimal*base
63.    Else
64.      Goto fini
65.    EndIf
66.  Case 97,98,99,100,101,102   ;"a" to "f"
67.    If base=16 Then
68.      temp#=temp#*base+c-87
69.      If decimal Then decimal=decimal*base
70.    Else
71.      Goto fini
72.    EndIf
73.  Default
74.    Goto fini
75.  End Select
76. .skip
77. Next
78. .fini
79. If decimal Then temp#=temp#/decimal
80. Return temp#*sign
81. End Function