javscript Q
- Started
- Last post
- 6 Responses
- OZute
I have 2 prompts creating variables:
value01 = prompt ('Enter value 1:', 3);
value02 = prompt ('Enter value 2:', 2);if nothing is entered in the prompt:
value01 = 3
and value02 = 2next step is to addition the integers:
result = value01 + value02;
alert(result);
and:result2 = value01 - value02;
alert(result2);The alert (result) gives as result: 32 instead of 5 i can't figure why?
The alert (result2) gives as result: 1 as I expected!
Whats happening here?
- welded0
I'm not an expert by any stretch, but it's clear that result is concatenating the numbers instead of adding them, so it must think they're strings. I've had a similar problem in the past, but can't find the file in question. The gist of it is you've got to convert it to a number. I *think* I just multiplied it by one, or something. I can't remember. :\
I'm sure there are better, smarter ways.
- OZute0
Thanx anyway
- rabattski0
welded is right. why subtracting works is because javascript can't substract strings so it assumes those are numbers.
anyways,
before you do the math do this:
value01 = value01 * 1
etc.
this turns it into a number. only if value01 contains numbers only.
- welded0
Come to think of it, I had the same sort of problem in an Excel formula.
Anyway, it's a bit of a bummer that the addition operator also concatenates. This wouldn't happen in, say, PHP.
- stewart0
solved?