Blubber
Blubber

Reputation: 1473

How to convert a string to a number

Is there a toInt, or parseInt function? There appears to be a StringToBinary, but I don't need a binary representation, I just want the number.

Upvotes: 0

Views: 1139

Answers (2)

user5992808
user5992808

Reputation:

Be aware, that Number() works in one case unexpected. Strings will converted to 0, but "0" also. You have no chance, to see the difference. It's written in the help file (A string beginning with letters has a numeric value of zero.), but it is not satisfactory.
I've made my own function, that exactly works, like Number(). But if you pass an expression, that is a string or starts with a string, this returns an numeric value of your choice (default: 0xDEADBEEF) and sets @error to 1.

; #FUNCTION# ====================================================================================================================
; Name ..........: _Number
; Description ...: Works like "Number()", but avoids to convert a string to number 0!
; Syntax ........: _Number($_Expression, $_Flag)
; Parameters ....: $_Expression    - An expression to convert into a number.
; ...............: $_iErrReturn    - The numeric return value in error case. Default: 0xDEADBEEF
; ...............:                   You get also the default value by passing "Default" or empty string instaed.
; ...............: $_Flag          - Can be one of the following:
; ...............:                   $NUMBER_AUTO (0) = (default) the result is auto-sized integer.
; ...............:                   $NUMBER_32BIT (1) = the result is 32bit integer.
; ...............:                   $NUMBER_64BIT (2) = the result is 64bit integer.
; ...............:                   $NUMBER_DOUBLE (3) = the result is double.
; Return values .: Success           The converted number, if $_Expression is a number or starts with a (un/signed) number.
; ...............: Failure           The Value from "$_iErrReturn", sets @error = 1   $_Expression is a string or starts with a string.
; Author ........: BugFix
; Remarks .......: In contrast to Number(), you get only a number, if $_Expression is a number or starts with it.
; ...............: Because 0 is also a number, Number() give unclear results:
; ...............: Number("foo") returns 0. Number("0") returns also 0. "0" converts to the real number 0, but "foo" also??
; ===============================================================================================================================
Func _Number($_Expression, $_iErrReturn=0xDEADBEEF, $_Flag=0)
    If $_iErrReturn = Default Or $_iErrReturn = '' Then $_iErrReturn = 0xDEADBEEF
    If StringRegExp($_Expression, '^(-\s\d|-\d|\d)') Then
        Return Number($_Expression, $_Flag)
    Else
        Return SetError(1, 0, $_iErrReturn)
    EndIf
EndFunc   ;==>_Number

Upvotes: 1

Blubber
Blubber

Reputation: 1473

I figured it out, use the Number() function.

Number("5") becomes 5.

Upvotes: 0

Related Questions