adding two quantities

R

Richard Cornford

Thomas 'PointedEars' Lahn said:
The correct use of eval(...) here is

var sum = eval("s1 + s2");

Isn't that equivalent to:-

var sum = s1 + s2;

and still string concatenation and not numeric addition?

Richard.
 
L

Lasse Reichstein Nielsen

("Correct" by what measure? It is not using eval on a runtime-supplied
Javascript expression, so by my measure it is wrong).
Isn't that equivalent to:-

var sum = s1 + s2;

and still string concatenation and not numeric addition?

Yes.

/L
 
L

Lasse Reichstein Nielsen

Thomas 'PointedEars' Lahn said:
Evertjan. said:
Mikhail Esteves wrote on 30 okt 2003 in comp.lang.javascript:

Never use eval, it is evil.

eval(...) *is* evil[tm] *unless* used for its intended purpose:

http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/toplev.html#1063795

That description isn't very specific about the intended purpose. The
four examples are, however, prime examples of when *not* to use eval.

Example 1: eval is simply not needed. This example is only there to
show how to write "eval(...)".

Example 2: The "getFieldName" function returns the field name. It
would be smarter to have a function that returns the field element
itself, since you can easily go from element to name. The other
direction is harder. They then use eval to go the other direction by
using the name as, apparently, a global variable!

Example 3: It is just as simple to use a thunk (function with no
argument). That will also make the return value explicit instead
of the confuzing way the result of the eval is found. Using a function
will make syntax errors apparent during loading instead of being hidden
until eval is called.
I.e.:
var delay = function(){if (x==5){alert('x is 42');z=42} else z=0;return z;};
document.write("<P>z is ",delay());

Example 4:
They use eval to access an object property instead of square bracket
notation. It suffers from all the short-commings of Example 3.
I.e., an equivalent, but much better solution is:
function setValue (textObject, newValue) {
document.forms[0][textObject].value = newValue;
}

If these examples are defining for the intended purpose of eval,
then eval is evil when used for its intended purpose.

/L
 
L

Lasse Reichstein Nielsen

Thomas 'PointedEars' Lahn said:
No. Please test before you post.

I did.
---
var s1="4";
var s2="5";
var sum = eval("s1+s2");
alert(sum);
---
It alerts "45", not "9".

Did you mean to write
var sum = eval(s1+"+"+s2);
?

/L
 
R

Richard Cornford

As the reference shows.

A reference that illustrates the use of eval by applying it
unnecessarily and/or inappropriately. Probably because contriving an
illustration of the appropriate use of eval would have taken a couple of
pages.
No. Please test before you post.

Pot - kettle.

<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
//from the OP:-
var s1="4";
var s2="5";
//from your post:-
var sum = eval("s1 + s2");
document.write('sum = '+sum+'<br>'); //output = 45
document.write('typeof sum = '+(typeof sum));//output = "string"
/*
Conclusion - var sum = eval("s1 + s2"); - performs string concatenation
and not numeric addition. And I was not alone in being able to see that
without testing it.
*/
</script>
</body>
</html>

It must be nice to be so confident that you are always right even when
contradicted by hard mechanical logic.

Richard.
 
D

Douglas Crockford

var newStr = eval(s1) + eval(s2);
As the reference shows.


No. Please test before you post.

You probably meant to write

var sum = eval(s1 + " + " + s2);

which is less wrong than your suggestion, but which does two concatenations
before invoking the compiler. This is a very bad way to perform addition on two
strings.

But more instructively, your misplaced confidence in eval() demonstrates that it
encourages faulty coding.

It is almost always wrong to use eval(). Most of the people using eval() use it
wrongly. I cite the above as an example.

http://www.crockford.com
 
F

Fabian

Douglas Crockford hu kiteb:
You probably meant to write

var sum = eval(s1 + " + " + s2);

which is less wrong than your suggestion, but which does two
concatenations before invoking the compiler. This is a very bad way
to perform addition on two strings.

I just checked my manual. Apparently, the following should work:

var sum = parseFloat(s1) + parseFloat(s2);

Im just a disinterested observer though. I just tested it and it seems
to work too. Note the capitalisation is important.
 
R

Richard Cornford

I just checked my manual. Apparently, the following should work:

var sum = parseFloat(s1) + parseFloat(s2);
Im just a disinterested observer though. I just tested it and
it seems to work too. Note the capitalisation is important.

The OP specifically stated that the result should be a string
representation of the result of the addition of the numeric values
represented by the original strings s1 and s2, and your result is
numeric, so not quite the whole answer and not substantially different
in effectiveness from the code Evertjan posted two days ago.

Solutions so far have stressed the importance of first converting the
strings s1 and s2 into numbers, for which any of the methods mentioned
in the FAQ are effective:-

<URL: http://jibbering.com/faq/#FAQ4_21 >

Whether parseFloat could be preferred over the other methods would
depend on information not included by the OP. parseFloat is certainly
slower than any of the methods that force type conversion by applying
unambiguously mathematical operators to the strings. On the other hand
it scores over those other options in that when presented with an empty
string it will return NaN while the type-converting methods return the
number zero. When the desire is to perform addition, adding zero when
there is no input string may be acceptable/harmless, while accidentally
multiplying or dividing by zero may be sufficiently incorrect that a
testable NaN result would be preferable. It all depends on the context
(and could also be addressed by examining the input strings).

Also, if it was known that s1 and s2 were always integers (representable
in about 52 bits) it may be possible to use parseInt, and if the integer
range was more limited (32 bit signed integers) then it would be
possible to consider some bitwise operations as possible additional
type-converting methods (though they should not be able to outperform
unary plus at forcing type-conversion (and the internal toInt32 function
has its own ideas about how to handle unexpected input)).

Richard.
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
Douglas Crockford hu kiteb:


I just checked my manual. Apparently, the following should work:

var sum = parseFloat(s1) + parseFloat(s2);

Im just a disinterested observer though. I just tested it and it seems
to work too. Note the capitalisation is important.

One should not choose a method merely on the basis that it seems to
work. That condition is necessary but not sufficient.

If there is any prospect of the string having been supplied by an
unreliable system (including a user) without subsequent full format
verification, one should consider what happens with invalid strings.
Different methods give different results.

F.X0.value = "6.7 tons"
Q = [parseFloat(F.X0.value), +F.X0.value] // result : 6.7,NaN

"3,14159" gives 3,NaN and three is clearly not what was hoped for;
yet it will give similar numerical results later.

"0XIDE" gives 0,NaN. "0XE" gives 0,14.

And

F.X0.value = "0077"
Q = [parseInt(F.X0.value), +F.X0.value] // result : 63,77
 
T

Thomas 'PointedEars' Lahn

Lasse said:
I did.
---
var s1="4";
var s2="5";
var sum = eval("s1+s2");
alert(sum);

/me 2
Did you mean to write
var sum = eval(s1+"+"+s2);
?

No, I had tested with s1 and s2 as number variables. Mea culpa.


PointedEars
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
On Sun, 2 Nov 2003 14:15:07 +0000

<snip>
Excellent point. What would you recommend? I would suspect that any
conversion from date, time, or number to string should have a mirror
method that converts the other direction for comparison.

It depends on what s1 and s2 represent.

Must they be all-digit strings? Is there an upper size limit? Can
there be a leading + or -? Are leading and/or trailing spaces to be
allowed? Is Hex to be allowed, or Octal?

Can one accept E-notation for integer quantities? If a Saturn V costs a
gigabuck, can one write 1e9 or must one use 1000000000?

If they can be fractional, what is the separator? How about thousands
separators? Is 1 000 000 allowed for a million?

It also depends on how important error actually is.

I would, generally, verify the format of the string with a RegExp -
OK = /(d{1,6})/.test(S) // crude example
Ans = +RegExp.$1

The RegExp must be tested both for accepting what should be accepted and
rejecting what should be rejected.

Note that eval(s1) has the possible advantage of allowing the entry of
expressions. A short American, asked to enter his height in
centimetres, may like to be able to type (5*12+3)*2.54 instead of
doing the arithmetic himself.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top