I just spent 4 frigging hours trying to get some numbers to add with vbscript.
It kept concatenating the numbers instead.
mills = 0
totmills = 0
do while … record … blah blah blah
totmills = mills + totmills
next record
Loop
The var mills = the numbers 12.159, 26.428, 3.997 etc.
totmills ended up being 12.15926.4283.997
when I changed it to -
totmills = 0 + mills + totmills
it worked.
What the hell? The + operator is for adding not concatenating. The & is for concatenating. I even tried it using FormatNumber. No help. Had to put that + 0 in there.
VBScript is untyped, so all variables are of the variant type. That means they can be string or numeric depending on what you put in them, and they will automatically be cast to the appropriate type for an operation.
Your do-while implies you’re doing something with database records or reading data from somewhere. Is it possible you’re reading string data into mills, which would cause the “+” operator to be treated as string concat instead of numeric add?
I’d cut the “0 +” kluge and use an explicit numeric cast like CSng( ) to convert to a single-precision number:
if IsNumeric(mills) then
totmills = totmills + CSng(mills)
end if
Mills is in an informix table, defined as a decimal number.
But VB script must be interpreting it as a string.
I did try using FormatNumber() on the mills var before adding it. No help.
A VBscript website said - ‘When one expression is numeric and the other is a string’ + operator will add. I set the totmills incrementer to 0 before the loop. So it meet this condition reguardless of how it interpreted mills. Yet it still concated.
Just tried the Csng() function, and it worked. So I can get that stupid + 0 out of there.
I think you misunderstand what FormatNumber() does. It will convert your number into a string. It’s whole purpose is to create a “printable” version of your number in a specific format without changing the underlying number. So saying myval=FormatNumber(myval,2) is equivalent to myval=CStr(CInt(myval*100)/100)).
Yep, you’re right. I wasn’t looking at it right. I gave that a shot because it kept concatenating the numbers. Didn’t look close enough for other functions.