Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to double in VBScript?

Tags:

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?

like image 267
Mark Allison Avatar asked Dec 15 '22 06:12

Mark Allison


2 Answers

"6.2.1" is not a Double formatted as a String. So CDbl() can't convert it. Your options are:

  1. 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"
  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
  3. Remove the "."s and CLng the resulting string; will break for versions like "6.10.2"
  4. 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"
like image 111
Ekkehard.Horner Avatar answered Feb 24 '23 13:02

Ekkehard.Horner


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)
like image 28
jonhopkins Avatar answered Feb 24 '23 12:02

jonhopkins