Maybe it's a newbie question, but if I have two strings, let's say s1="4"
and s2="5", how can I get a new string of value "9", that is, add the two
numbers. If I type:
var newStr = s1 + s2
all I get is a concatenation.
How to really add them?
Thx 32 4089
yukatan, on Thu, 30 Oct 2003 20:59:09 +0100, had to say: Maybe it's a newbie question, but if I have two strings, let's say s1="4" and s2="5", how can I get a new string of value "9", that is, add the two numbers. If I type: var newStr = s1 + s2 all I get is a concatenation. How to really add them? Thx
Try:
var newStr = eval(s1) + eval(s2);
Cheers,
Mikhail
Mikhail Esteves wrote on 30 okt 2003 in comp.lang.javascript : yukatan, on Thu, 30 Oct 2003 20:59:09 +0100, had to say:
Maybe it's a newbie question, but if I have two strings, let's say s1="4" and s2="5", how can I get a new string of value "9", that is, add the two numbers. If I type: var newStr = s1 + s2 all I get is a concatenation. How to really add them? Thx
Try:
var newStr = eval(s1) + eval(s2);
Never use eval, it is evil.
Use:
var newStr = 1*s1 + 1*s2
or
var newStr = +s1 + +s2
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
> >> Maybe it's a newbie question, but if I have two strings, let's say s1="4" and s2="5", how can I get a new string of value "9", that is, add the two numbers. If I type: var newStr = s1 + s2 all I get is a concatenation. var newStr = eval(s1) + eval(s2);
Never use eval, it is evil.
Use:
var newStr = 1*s1 + 1*s2
or
var newStr = +s1 + +s2
The last form is definitely the best. I recommend adding parens to it
var newStr = +s1 + (+s2);
so that it will not be confused with
var newStr = +s1 ++s2; http://www.crockford.com
Evertjan., on Thu, 30 Oct 2003 20:35:53 +0000, had to say: Never use eval, it is evil.
I've heard this before. But why exactly is it evil?
Cheers,
Mikhail
Mikhail Esteves wrote on 30 okt 2003 in comp.lang.javascript : Evertjan., on Thu, 30 Oct 2003 20:35:53 +0000, had to say:
Never use eval, it is evil.
I've heard this before. But why exactly is it evil?
Because [Warning: unsubstantiated]:
1 it takes a lot of unnecessary processing time.
[I think to set up a new instance of javascript]
2 if you make an code error the errorhandling will be hazardous.
Anyone that knows more about these evils ??
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Evertjan., on Thu, 30 Oct 2003 20:53:21 +0000, had to say: Because [Warning: unsubstantiated]:
1 it takes a lot of unnecessary processing time. [I think to set up a new instance of javascript]
2 if you make an code error the errorhandling will be hazardous.
Anyone that knows more about these evils ??
From Googling around, I gather it's evil only when used wrong. Below is
an older (1998) comp.lang.javascript posting:
On Fri, 27 Mar 1998 13:52:38 +0000, Nick Fitzsimons
<ni************@atlasinteractive.com> wrote:
Mike Shaver wrote: Christopher Thompson wrote: > Try using eval().
No! Don't use eval! Eval is evil, and should be used only in the direst of circumstances! Bad Christopher!
Mike, I know that eval was buggy or totally non-functional on certain NN 2 versions/platforms, but I'd never thought of it as being actually *evil* - can you expand a little on your chastisement of Christopher, as although I almost never use eval myself, I don't want to stray too far from the path of righteousness - well, not in my coding, anyway :-)
Who knows what crawled up Mike's ass in this statement, but I know I
wouldn't categorize eval as evil (maybe he liked the pun :-). It has
been quite annoying for some who did not use it correctly with respect
to the platform, or who overused it, but it can be really handy at
times.
First, elaboration of the above
1) IE - must be the full line. There are so many variations to this
damn browser that I am sure there are exceptions, but the safe rule is
to only use eval for a complete statement.
2) Overuse - eval is apparently much slower than it ought to be, I
haven't run any benchmarks, but others have indicated this to be so,
so overuse means performance hits. Bad enough that the browser may be
living on a 486 with <= 16M Ram that you shouldn't add insult to
injury.
That said, eval can come in handy for some key things:
1) Backward compatibility with the void function
function myVoid(stm) {
eval(stm);
}
2) Variable variables
for (i=0;i<5;i++) {
eval ("var var" +i+ " = " i);
}
On the other hand, arrays can be used to achieve a similar effect, but
it isn't exactly the same.
var vars = new Array();
for (i=0;i<5;i++) {
vars[i] = i;
}
And, eval can come in handy with image swapping, but, there again,
arrays can be used with success as well.
The gist is that while they aren't evil, they should be used, as Mike
indicated, with moderation.
"Evertjan." <ex**************@interxnl.net> wrote in message
news:Xn********************@194.109.133.29...
<snip> Because [Warning: unsubstantiated]:
1 it takes a lot of unnecessary processing time.
<snip>
Testing the speed of various string to number type converting operations
revealed that the use of - evel - is about 40 times slower than forcing
type conversion with the unary plus operator and at least 5 times slower
than the worst or the other alternatives. It is also the only string to
number type converting method that has unpredictable output if the input
is not a string representation of a number.
Richard.
Richard Cornford, on Thu, 30 Oct 2003 21:32:35 +0000, had to say: Testing the speed of various string to number type converting operations revealed that the use of - evel - is about 40 times slower than forcing type conversion with the unary plus operator and at least 5 times slower than the worst or the other alternatives. It is also the only string to number type converting method that has unpredictable output if the input is not a string representation of a number.
Are there links to any such tests? As in when, which browser, what machine
and so on these tests were run? The baseless claim that 'eval is evil'
looks like it's been going on for years now.
Any info would be appreciated.
Mikhail
"Mikhail Esteves" <ma**@REMOVETHIS.thejackol.com> wrote in message
news:pa****************************@uni-berlin.de...
<snip> From Googling around, I gather it's evil only when used wrong.
There are no circumstances under which it is _necessary_ to use eval.
The few circumstances under which it is appropriate to use eval is where
it is necessary to execute JavaScript source code when the contents of
that source code cannot be predicted. That is an extremely rare
condition and will almost never be the case in a normal Internet
browsers scripting context.
Below is an older (1998) comp.lang.javascript posting:
That was a very long time ago. Netscape 4 and IE 4 were brand new and
some kludge workarounds might have been needed or really ancient
browsers. These days anyone attempting to use a browser much older than
Netscape 4 on the Internet is not finding the experience at all
productive.
On Fri, 27 Mar 1998 13:52:38 +0000, Nick Fitzsimons <ni************@atlasinteractive.com> wrote:
<snip> That said, eval can come in handy for some key things:
1) Backward compatibility with the void function
void was introduced in JavaScript 1.1 and is an operator and not a
function.
function myVoid(stm) { eval(stm); }
This function in no way mimics the action of the void operator (even if
it was treated as a function) and seems very likely to generate a run
time error if used in the place of the void operator. Simply using -
function myVoid(param){ return; } - would be a better substitute for the
void operator.
2) Variable variables for (i=0;i<5;i++) { eval ("var var" +i+ " = " i); }
This is simply unnecessary if the variable in question is a global
variable. In any event, the functionality of dynamically creating
function local named references to values can easily be achieved by
other means, and the result will be more efficient than this eval
aproach.
<snip>And, eval can come in handy with image swapping, but, there again, arrays can be used with success as well.
I just don't see this. If it was true 5 years ago it certainly is not
relevant now.
The gist is that while they aren't evil, they should be used, as Mike indicated, with moderation.
eval does not need to be used in moderation, it should be used _only_
when it is appropriate. But that will be so infrequently that any desire
to use it in code should be looked upon as indicative of the author
missing a better (usually much better) alternative.
Richard.
Mikhail Esteves <ma**@REMOVETHIS.thejackol.com> writes: From Googling around, I gather it's evil only when used wrong. Below is an older (1998) comp.lang.javascript posting:
I feel a little bad about commenting on something written five years ago.
Mostly because the author won't get to defend his position :)
First, elaboration of the above
1) IE - must be the full line. There are so many variations to this damn browser that I am sure there are exceptions, but the safe rule is to only use eval for a complete statement.
I never heard that before, and I don't know what the problem is.
2) Overuse - eval is apparently much slower than it ought to be, I haven't run any benchmarks, but others have indicated this to be so, so overuse means performance hits. Bad enough that the browser may be living on a 486 with <= 16M Ram that you shouldn't add insult to injury.
This is still the case, except perhaps for the "ought to". Eval is
slow! It is not surpricing, since it has to parse the string before
evaluating it.
That said, eval can come in handy for some key things:
1) Backward compatibility with the void function
function myVoid(stm) { eval(stm); }
"void" is not a function, but an operator. There are lots of different
ways to do the same thing without eval.
instead of
myVoid("<statements>")
you can use, e.g.:
function(){<statements>}();
or
{statements;undefined}
2) Variable variables for (i=0;i<5;i++) { eval ("var var" +i+ " = " i); }
BAD coding style. Very! Sure, you can do it, but you shouldn't.
Make one variable containing an array. That is probably what you needed
to begin with.
On the other hand, arrays can be used to achieve a similar effect, but it isn't exactly the same.
No, it's far better. Doing it with eval will also mean that you need
eval to reference the variables - eval("var"+i) - so there is no reason
not to use an array instead.
And, eval can come in handy with image swapping, but, there again, arrays can be used with success as well.
I can't see how eval can do anything that an array can't do better.
The gist is that while they aren't evil, they should be used, as Mike indicated, with moderation.
I disagree. They should be used only when *absolutely* necessary, i.e.,
when you need to evaluate Javascript code supplied as a string (most likely
as input by a user or fetched over the net).
Very few people write pages where eval is necessary.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Mikhail Esteves said: Richard Cornford, on Thu, 30 Oct 2003 21:32:35 +0000, had to say:
Testing the speed of various string to number type converting operations revealed that the use of - evel - is about 40 times slower than forcing type conversion with the unary plus operator and at least 5 times slower than the worst or the other alternatives. It is also the only string to number type converting method that has unpredictable output if the input is not a string representation of a number.
Are there links to any such tests? As in when, which browser, what machine and so on these tests were run? The baseless claim that 'eval is evil' looks like it's been going on for years now.
Any info would be appreciated.
Why do you assume that it's baseless?
It should be obvious to anybody who understands what eval() does
that it's going to take a lot longer to compile an expression and
evaluate it than to evaluate a precompiled expression.
You can create your own time comparison with a few lines of code.
Lee, on Thu, 30 Oct 2003 14:36:16 -0800, had to say: Why do you assume that it's baseless?
Me bad. That was a genuine mistake :)
"Mikhail Esteves" <ma**@REMOVETHIS.thejackol.com> wrote in message
news:pa****************************@uni-berlin.de... Testing the speed of various string to number type converting operations revealed that the use of - evel - is about 40 times slower than forcing type conversion with the unary plus operator and at least 5 times slower than the worst or the other alternatives. ...
<snip> Are there links to any such tests? As in when, which browser, what machine and so on these tests were run?
Try it for yourself, any browser. The machine is not important when
gathering relative speed values:-
<URL: http://www.litotes.demon.co.uk/js_sp...gToNumber.html >
The baseless claim that 'eval is evil' looks like it's been going on for years now.
eval is evil and always has been. This group continues to actively
campaign against its abuse because it server to discourage new script
authors from learning to do things properly. People promote eval because
it "works", in the broadest possible sense of the word, but is its use
correct? Take the code you posted to this thread:-
var newStr = eval(s1) + eval(s2);
Apart from the fact that, when it "works", it still does not fulfil the
OPs requirement as the output is of numeric type and not a string, which
brings into question the use of "newStr" as an identifier for the
result. The eval function may react in almost any way if the s1 or s2
values are no actually strings that represent numbers in JavaScript
source code. When so many alternative string to number type-converting
methods exist and they _all_ have predictable, specified and documented
output if the input does not happen to be a string representation of a
number, then eval is objectively the worst string to number
type-converting method to use. So why promote its use? Because it
"works" (when it works)?
But eval abuse does not only shelter people from learning better
techniques, it also encourages a "mystical incantation" approach to
programming, resulting in people wrapping the eval function around all
sorts of weird and wonderful expressions, and because doing that won't
necessarily make things worse and will often mask errors this habit
propagates throughout their code.
No one benefits from the use of eval, not the user (burdened with slow,
processor intensive code and excessive downloads), not the programmer
(screened from learning to do their job well) and definitely not the
posters on this group. If that results in a pejorative epithet being
attached to the eval function then that is not really surprising.
Richard.
Mikhail Esteves <ma**@REMOVETHIS.thejackol.com> writes: Are there links to any such tests?
I am sure there are several. For the fun of it, I just made my own:
<URL:http://www.infimum.dk/privat/convertTimer.html>
It lets you test for yourself. On my machine, with the default settings,
IE and Opera are both approximatly 80 times slower using eval than using
unary plus. In Netscape 4 and Mozilla, the difference is only 9 times.
As in when, which browser, what machine and so on these tests were run?
Mine is a 1GHz Athlon running Windows XP Pro. I did a quick test in Opera 7.21,
IE 6, Mozilla FB 0.7 and Netscape 4.80.
The baseless claim that 'eval is evil' looks like it's been going on for years now.
It's not baseless. It's always been evil :)
My primary problems with using eval are:
1) Using it doesn't adequatly separate code and data. This makes bugs
easier to make and harder to find.
2) It is too powerful a tool most of the jobs it is used for, making
it too easy to shoot oneself in the foot.
3) There are other, simpler and more specialized, tools to do the same
jobs.
Any info would be appreciated.
You mean that you are not certain that the claims are baseless? :)
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
> >From Googling around, I gather it's evil only when used wrong. There are no circumstances under which it is _necessary_ to use eval. The few circumstances under which it is appropriate to use eval is where it is necessary to execute JavaScript source code when the contents of that source code cannot be predicted. That is an extremely rare condition and will almost never be the case in a normal Internet browsers scripting context. Below is an older (1998) comp.lang.javascript posting:
By Google, the first use of the phrase "eval is evil" in this group was Mar 27,
1998 by jason olmsted. Clearly, the problems with the misuse of eval have been
understood for a long time. http://www.ecmascript.org
JRS: In article <pa****************************@uni-berlin.de>, seen in
news:comp.lang.javascript, Mikhail Esteves <ma**@REMOVETHIS.thejackol.co
m> posted at Fri, 31 Oct 2003 01:32:23 :- yukatan, on Thu, 30 Oct 2003 20:59:09 +0100, had to say:
Maybe it's a newbie question, but if I have two strings, let's say s1="4" and s2="5", how can I get a new string of value "9", that is, add the two numbers. If I type: var newStr = s1 + s2 all I get is a concatenation. How to really add them? Thx
Try:
var newStr = eval(s1) + eval(s2);
No-one has given the most generally useful advice, which is "Read the
FAQ before asking or answering questions here; this one is dealt with
in Sec 4.21".
That applies even to the most experienced answerers, who think they know
everything; if they are right, and do know everything, then they might
be able to suggest improvements in the FAQ.
Use of eval is treated in FAQ Sec 4.40, linking to 4.39, linking to
Cornford on addressing.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
Mikhail Esteves wrote: var newStr = eval(s1) + eval(s2);
The correct use of eval(...) here is
var sum = eval("s1 + s2");
PointedEars
Evertjan. wrote: Mikhail Esteves wrote on 30 okt 2003 in comp.lang.javascript: var newStr = eval(s1) + eval(s2);
Never use eval, it is evil.
eval(...) *is* evil[tm] *unless* used for its intended purpose: http://devedge.netscape.com/library/...v.html#1063795
PointedEars
"Thomas 'PointedEars' Lahn" <Po*********@web.de> wrote in message
news:3F**************@PointedEars.de... var newStr = eval(s1) + eval(s2);
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.
"Richard Cornford" <Ri*****@litotes.demon.co.uk> writes: "Thomas 'PointedEars' Lahn" <Po*********@web.de> wrote in message news:3F**************@PointedEars.de...var newStr = eval(s1) + eval(s2); The correct use of eval(...) here is
var sum = eval("s1 + s2");
("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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Thomas 'PointedEars' Lahn <Po*********@web.de> writes: Evertjan. wrote:
Mikhail Esteves wrote on 30 okt 2003 in comp.lang.javascript: var newStr = eval(s1) + eval(s2);
Never use eval, it is evil.
eval(...) *is* evil[tm] *unless* used for its intended purpose:
http://devedge.netscape.com/library/...v.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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Lasse Reichstein Nielsen wrote: "Richard Cornford" <Ri*****@litotes.demon.co.uk> writes: "Thomas 'PointedEars' Lahn" <Po*********@web.de> wrote in message news:3F**************@PointedEars.de... >>var newStr = eval(s1) + eval(s2); > >The correct use of eval(...) here is > > var sum = eval("s1 + s2"); ("Correct" by what measure?
As the reference shows.
Isn't that equivalent to:-
var sum = s1 + s2;
and still string concatenation and not numeric addition?
Yes.
No. Please test before you post.
PointedEars
Thomas 'PointedEars' Lahn <Po*********@web.de> writes: 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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
"Thomas 'PointedEars' Lahn" <Po*********@web.de> wrote in message
news:3F************@PointedEars.de...
<snip> The correct use of eval(...) here is
var sum = eval("s1 + s2");
("Correct" by what measure?
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. Isn't that equivalent to:-
var sum = s1 + s2;
and still string concatenation and not numeric addition?
Yes.
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.
> >> >>var newStr = eval(s1) + eval(s2); > >The correct use of eval(...) here is > > var sum = eval("s1 + s2");
("Correct" by what measure?
As the reference shows.
Isn't that equivalent to:-
var sum = s1 + s2;
and still string concatenation and not numeric addition?
Yes.
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
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.
--
--
Fabian
Visit my website often and for long periods! http://www.lajzar.co.uk
"Fabian" <la****@hotmail.com> wrote in message
news:bo*************@ID-174912.news.uni-berlin.de...
<snip> 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.
Lasse Reichstein Nielsen wrote: Thomas 'PointedEars' Lahn <Po*********@web.de> writes: 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".
/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
JRS: In article <bo*************@ID-174912.news.uni-berlin.de>, seen in
news:comp.lang.javascript, Fabian <la****@hotmail.com> posted at Sun, 2
Nov 2003 08:16:52 :- 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.
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
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.
On Sun, 2 Nov 2003 14:15:07 +0000
Dr John Stockton <sp**@merlyn.demon.co.uk> wrote:
<snip> 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.
<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.
--
Life is an offensive, directed against the repetitious mechanism of the
Universe.
--Alfred North Whitehead (1861-1947)
JRS: In article <20******************************@tcac.net>, seen in
news:comp.lang.javascript, Albert Wagner <al******@tcac.net> posted at
Sun, 2 Nov 2003 15:05:01 :- On Sun, 2 Nov 2003 14:15:07 +0000 Dr John Stockton <sp**@merlyn.demon.co.uk> wrote: <snip> 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. <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.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: cjm |
last post by:
I have two problems that I suspect will be bread-and-butter problems for the
more experienced guys on here, but I'm not the greatest with js.
NB: Code snippets at the bottom
The first problem...
|
by: 6thirty |
last post by:
Hi,
I've created a stocktaking database using Access XP. This is indexed by two
fields - part number and shelf location.
I am currently inputting all the data via a form. When I have entered a...
|
by: Shannan Casteel via AccessMonster.com |
last post by:
I have a table called tblParttest. It has fields PartNo, PartNo2, PartNo3, ..
.., PartNo25 and Quantity, Quantity2, Quantity3, ...Quantity25.
If I enter "1234" into the PartNo field and "4" into...
|
by: Shannan Casteel via AccessMonster.com |
last post by:
I set up two tables (one with the regular claim
info and another with ClaimNumber, PartNumber, and QuantityReplaced). The
ClaimNumber is an autonumber and the primary key in both tables. I made a...
|
by: Jim Heavey |
last post by:
Trying to figure out the technique which should be used
to add rows to a datagrid. I am thinking that I would
want an "Add" button on the footer, but I am not quite
sure how to do that. Is that...
|
by: Robert Dodier |
last post by:
Hello,
I am interested in the problem of communicating physical quantities,
e.g. between a web service and its client.
I am sure there has been a lot of work on that,
so there seems no need for...
|
by: patrickdepinguin |
last post by:
Hi,
I need to write large quantities of data to a file in C. The data comes from statistics that are continuously gathered from a simulator, and in order to not slow the whole thing down I would...
|
by: Gen |
last post by:
Hello there,
I am a leader of a team, developing business application based on the
ASP.NET platform. Now we need to add cash register support to the
application and it seems to be a bit of a...
|
by: geolemon |
last post by:
I have a form/subform used for inventory management.
It is a bound form.
The error:
I don't understand what this means.
How the form is intended to work:
When you select a part number in...
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome former...
|
by: ryjfgjl |
last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
| |