如何将字符串转换为数字

问题描述 投票:0回答:2

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

autoit
2个回答
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

0
投票

我想通了,使用Number()函数。

Number("5")成为5。

© www.soinside.com 2019 - 2024. All rights reserved.