How to convert string to double in VBScript? - vbscript

I need to write some code in VBScript and have a version number string in a text file that I need to compare against. If I write this code as a test:
option explicit
Dim VersionString
VersionString = "6.2.1"
Dim Version
Version = CDbl (VersionString)
Version = Version * 100
I get an error on the CDbl line:
Microsoft VBScript runtime error: Type mismatch: 'CDbl'
How should I read and compare this string value?

"6.2.1" is not a Double formatted as a String. So CDbl() can't convert it. Your options are:
treat versions as strings; ok if you only need to compare for equality, bad if you need "6.9.1" to be smaller that "6.10.2"
Split() the string on "." and deal with the parts (perhaps converted to Integer/Long) separately; you'll need to write a comparison function for such arrays
Remove the "."s and CLng the resulting string; will break for versions like "6.10.2"
Split() the string on "*" and multiply + add the 'digits' to get one (integer) version number (6 * 100 + 2 * 10 + 1 * 1 = 621 for your sample); may be more complex for versions like "15.00.30729.01"

The conversion to a double isn't working because there are two decimal points in your string. To convert the string, you will have to remove one or both of them.
For this, you can use the Replace function. The syntax for Replace is
Replace(string, find, replacewith [, start [, count [, compare]]])
where string is the string to search, find is the substring to find, replacewith is the substring to replace find with, start is an optional parameter specifying the index to start searching at, count is an optional parameter specifying how many replaces to make, and compare is an optional parameter that is either 0 (vbBinaryCompare) to perform a binary comparison, or 1 (vbTextCompare) to perform a textual comparison
' Remove all decimals
Version = CDbl(Replace(VersionString, ".", "")
' Remove only the first decimal
Version = CDbl(Replace(VersionString, ".", "", 1, 1)
' Remove only the second decimal
Version = CDbl(Replace(VersionString, ".", "", 3, 1)

Related

Returning Values of Varying Length Between Two Characters with VBS [duplicate]

This question already has an answer here:
vbscript split string with colon delimiter
(1 answer)
Closed 1 year ago.
I am trying to come up with a method for extracting information from a file heading. The overall naming convention of the file heading will remain the same but portions of the heading will vary in character length. Below are two possible examples of such file headings:
012345678-012345-xxxx-yyyyy.txt
012345678-012345-xxx-yyyyyy.txt
Is there a way to extract values from these file headings such that it returns whatever appears between the second and third hyphen? Using the examples above it would return:
xxxx
xxx
Furthermore, is it possible to extract the values between the final hyphen and the period? Using the example above it would return:
yyyyy
yyyyyy
Extracting values is trivial when the character lengths are fixed, but I don't know if it's possible to do a similar extraction when the character lengths vary. I would normally use something like this to extract the information from a fixed-length naming convention but don't know how to adapt it to something where the character lengths change. For example, the snippet below is a function which extract the first nine characters in a file heading (in this case it would extract '012').
Function getthething(foo)
getthething = Mid(foo,1,3)
End Function
Any guidance would be very appreciated. Thank you.
You can do all of this using the Split function. Here's a wrapper function that simplifies things:
Function GetField(p_sText, p_sDelimiter, p_iIndex)
Dim arrFields
arrFields = Split(p_sText, p_sDelimiter)
If UBound(arrFields) >= (p_iIndex - 1) Then
GetField = arrFields(p_iIndex - 1)
Else
GetField = ""
End If
End Function
You can use this function like this:
Dim sFileName
Dim sYs
sFileName = GetField("012345678-012345-xxxx-yyyyy.txt", ".", 1)
sYs = GetField(sFileName, "-", 4)
MsgBox sYs
or simply:
MsgBox GetField(GetField("012345678-012345-xxxx-yyyyy.txt", ".", 1), "-", 4)

How to convert format of number from English to Italian with VBScript?

I need to convert the English numbering to Italian.
I tried using multiple replacements but I don't think it's the right method.
price = Replace(price, ".", ",")
The problem is that when I have too large numbers I get replaced several times and the wrong numbers come up.
For example:
English version: 3,450.108
After replacement: 3,450,108 (but it's wrong)
Correct format: 3.450,102
Would not recommend manually replacing values in an attempt to get the correct format when VBScript can already do it for you using the SetLocale() Function in conjunction with the FormatNumber() Function which will return the string representation of that number for the specific locale.
Note: Remember that the actual value and how a value is displayed are two separate things (see the example below).
Option Explicit
Const decimalplaces = 3
Dim price: price = 3450.108 'This is the raw value from your data source.
Call SetLocale("en-gb")
Call WScript.Echo("English (UK) price: " & FormatNumber(price, decimalplaces))
Call SetLocale("it-it")
Call WScript.Echo("Italian price: " & FormatNumber(price, decimalplaces))
Output:
English (UK) price: 3,450.108
Italian price: 3.450,108
If you want to swap 2 delimiter characters you need to use a temp character for the second one, otherwise you won't be able to distinguish between the original second delimiter and the replaced first one.
price = Replace(price, ".", "_")
price = Replace(price, ",", ".")
price = Replace(price, "_", ",")

In TI-BASIC, how do I add a variable in the middle of a String?

I am wondering how to make something where if X=5 and Y=2, then have it output something like
Hello 2 World 5.
In Java I would do
String a = "Hello " + Y + " World " + X;
System.out.println(a);
So how would I do that in TI-BASIC?
You have two issues to work out, concatenating strings and converting integers to a string representation.
String concatenation is very straightforward and utilizes the + operator. In your example:
"Hello " + "World"
Will yield the string "Hello World'.
Converting numbers to strings is not as easy in TI-BASIC, but a method for doing so compatible with the TI-83+/84+ series is available here. The following code and explanation are quoted from the linked page:
:"?
:For(X,1,1+log(N
:sub("0123456789",ipart(10fpart(N10^(-X)))+1,1)+Ans
:End
:sub(Ans,1,length(Ans)-1?Str1
With our number stored in N, we loop through each digit of N and store
the numeric character to our string that is at the matching position
in our substring. You access the individual digit in the number by
using iPart(10fPart(A/10^(X, and then locate where it is in the string
"0123456789". The reason you need to add 1 is so that it works with
the 0 digit.
In order to construct a string with all of the digits of the number, we first create a dummy string. This is what the "? is used
for. Each time through the For( loop, we concatenate the string from
before (which is still stored in the Ans variable) to the next numeric
character that is found in N. Using Ans allows us to not have to use
another string variable, since Ans can act like a string and it gets
updated accordingly, and Ans is also faster than a string variable.
By the time we are done with the For( loop, all of our numeric characters are put together in Ans. However, because we stored a dummy
character to the string initially, we now need to remove it, which we
do by getting the substring from the first character to the second to
last character of the string. Finally, we store the string to a more
permanent variable (in this case, Str1) for future use.
Once converted to a string, you can simply use the + operator to concatenate your string literals with the converted number strings.
You should also take a look at a similar Stack Overflow question which addresses a similar issue.
For this issue you can use the toString( function which was introduced in version 5.2.0. This function translates a number to a string which you can use to display numbers and strings together easily. It would end up like this:
Disp "Hello "+toString(Y)+" World "+toString(X)
If you know the length of "Hello" and "World," then you can simply use Output() because Disp creates a new line after every statement.

Vb6 .text property for textbox required

I am trying to convert letters to numbers.
I have a sub which ensures only numbers are put into the textbox.
My questions is will the following code work. I have a textbox(for numbers) and combobbox(for letters)
Dim sha As String
Dim stringposition As Long
Dim EngNumber As Long
sha = "abcdefghifjklmnopqrstuvwxyz"
stringposition = InStr(1, sha, Mid(1, cmbEngletter.Text, 1))
MsgBox "stringposition"
EngNumber = (txtManuNo.Text * 10) + stringposition
My only question above would be will the multiplication work with a .text. I believe it won't because it is a string. Please advise then on how to deal with a situation.
You can use CLng() to convert a string to a Long variable
CLng() will throw an error though if it doesn't like the contents of the string (for example if it contains a non-numeric character), so only use it when you are certain your string will only contain numbers
More forgiving is it to use Val() to convert a string into a numeric variable (a Double by default)
I also suggest you look into the following functions:
Asc() : returns the ASCII value of a character
Chr$() : coverts an ASCII value into a character
Left$() : returns the first characters of a string
CStr() : convert a number into a string
I think in your code you mean to show the contents of your variable stringposition instead of the word "stringposition", so you should remove the ""
I do wonder though what you are trying to accomplish with your code, but applying the above to your code gives:
Dim sha As String
Dim stringposition As Long
Dim EngNumber As Long
sha = "abcdefghifjklmnopqrstuvwxyz"
stringposition = InStr(1, sha, Left$(cmbEngletter.Text, 1))
MsgBox CStr(stringposition)
EngNumber = (Val(txtManuNo.Text) * 10) + stringposition
I used Val() because I am not certain your txtManuNo will contain only numbers
To ensure an user can only enter numbers you can use the following code:
Private Sub txtManuNo_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case vbKeyBack
'allowe backspace
Case vbKey0 To vbKey9
'allow numbers
Case Else
'refuse any other input
KeyAscii = 0
End Select
End Sub
An user can still input non-numeric charcters with other methods though, like copy-paste via mouse actions, but it is a quick and easy first filter

Remove email address from string in Ruby

I have the following code which is supposed to be removing a particular email address from a string if it exists. The problem is i get the error "invalid range "y-d" in string transliteration (ArgumentError)" which I assume is because it's treating my input as a regex. I will need to do this delete by a variable in the actual code, not a string literal but this is a simplified version of the problem.
So how do I properly perform this operation?
myvar = "test1#my-domain.com test2#my-domain.com"
myvar = myvar.delete("test1#my-domain.com")
Try
myvar = "test1#my-domain.com test2#my-domain.com"
myvar = myvar.gsub("test1#my-domain.com", '').strip
String#delete(str) does not delete the literal string str but builds a set out of individual characters of str and deletes all occurrences of these characters. try this:
"sets".delete("test")
=> ""
"sets".delete("est")
=> ""
The hyphen has a special meaning, it defines a range of characters. String#delete("a-d") will delete all occurrences of a,b,c and d characters. Range boundary characters should be given in ascending order: you should write "a-d" but not "d-a".
In your original example, ruby tries to build a character range from y-d substring and fails.
Use String#gsub method instead.
You can do it like this
myvar = "test1#my-domain.com test2#my-domain.com"
remove = "test1#my-domain.com"
myvar.gsub!(remove, "")

Resources