-
I just know I'm going to sound completely ignorant, but how does one go about converting a negative integer to a positive?
Also, is it possible to move a number-only string (like 15) to an integer variable? Example:
Code:
Dim Blah as Integer
Dim BlahString as String
BlahString = "15"
Blah = BlahString
Obviously, VB chokes on this with a type mismatch. Any wisdom you could share would be helpful, thanks very much.
- Evan Sims
-
Dim intMyInteger As Integer
Dim strMyString As String
strMyString = "-15"
intMyInteger = Val(strMyString)
' Make a postive integer negative or a negative integer positive
intMyInteger = intMyInteger * -1
MsgBox intMyInteger
-
Code:
'convert to positive
If iNum < 0 Then
iNum = iNum * -1
End If
'string to integer
If IsNumeric(stNum) Then
iNum = CInt(stNum)
End If
'or another way
iNum = Val(stNum)
-
Val() converts a string to a Double, so it's a good idea to use CInt, CLng, CSng, CByte whenever possible because they consume less memory.
[Edited by Megatron on 08-21-2000 at 01:28 PM]
-
Instead of multipling a negative number with -1 (this would turn a positive number into a negative as well) you can use the Abs function (it always returns a positive value):
Code:
Dim i As Integer
i = -3
i = Abs(i)
-
I agree with Megatron that it's usually better to use the conversion function in most cases but the Val function could be used with any string that begins with a number:
Code:
int iNum%
iNum = Val(" 127 01abcdef")
The above code would return 12701 but would have raised an error if you would have use the CInt function.
-
ABS
ABS is the same as
Code:
Number * Sgn(Number)
while Sgn is the sign +1 or -1 for the number, or 0 for 0.
-
Re: ABS
Quote:
Originally posted by kedaman
ABS is the same as
Code:
Number * Sgn(Number)
while Sgn is the sign +1 or -1 for the number, or 0 for 0.
This is true but calling Sgn and multiply it with Number is slightly slower then calling the Abs function.
-
Nope, I think it's the other way round, but i did some tests and they were about the same
-
You guys have the negative to positive thing covered very well, using Abs and Sgn; and the conversion functions like Val and Cxxx are the proper way to convert data from one type to another. However, one other thing bears mentioning in reference to one of Evan's original questions: the issue of VB's "evil type conversion". The behavior of VB from version 4 on up pretty much lets you assign anything to anything and if it can make the conversion, it will; you'll only get the "type mismatch" error if the data in fact cannot be converted. Evan's original code should actually work:
Quote:
Code:
Dim Blah as Integer
Dim BlahString as String
BlahString = "15"
Blah = BlahString