如何将字符串转换为数字

时间:2018-06-21 20:58:59

标签: autoit

是否有toInt或parseInt函数?似乎有一个StringToBinary,但是我不需要二进制表示形式,我只想要数字。

2 个答案:

答案 0 :(得分:1)

请注意,Number()在一种情况下无法正常工作。字符串将转换为0,但也将转换为“ 0”。您没有机会看到差异。它写在帮助文件(A string beginning with letters has a numeric value of zero.)中,但并不令人满意。
我已经制作了自己的函数,可以像Number()一样正常工作。但是,如果您传递的表达式是字符串或以字符串开头,则会返回您选择的数值(默认值:0xDEADBEEF),并将@error设置为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

答案 1 :(得分:0)

我知道了,使用Number()函数。

Number("5")变为5。