Mick said:
Erwin Moller wrote:
val1 = document.forms["myform"].field1.value;
val2 = document.forms["myform"].field2.value;
// do some calculation
myNewValue = val1 + val2;
The above will concatenate the strings, probably not what you want.
myNewValue = eval(val1) + eval(val2); // Not kosher but effective
Most of possible techniques for converting strings into numbers have
well specified behaviour whenever the input cannot be interpreted as a
number. But - eval - can do (literally) anything (including throwing
exceptions) and return anything.
If javascript did not include numerous alternative method of converting
strings into numbers it would still only be acceptable to apply - eval -
to user input that was expected to resemble a number if that input was
first examined to ensure that it conformed to an acceptable format (fore
example, with a regular expression).
As javascript does offer multiple alternative method of string to number
conversion it would be best to understand their mechanism, especially in
the handling of unexpected input and choose one suited to the context.
Probably combined with a regular expression examination of the user
input so that unexpected or unusual input could be well handled.
myNewValue = parseFloat(val1) + parseFloat(val2);
<snip>
Consider what happens if the user enters - 1,234.56 -, which could be
acceptable (and not unexpected) user input, but will not be well handled
by any string to number method. parseFloat/Int will consider it 1, -
eval - would return 234.56, while type-converting with unary plus or
the - Number - function will return NaN.
Richard.