473,569 Members | 2,879 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why math wont work?

sorry for the simple question, haven't done this in a while. when I use the
following script it keeps displaying the value of "x" like a string. for
example, if I type the number 7 in the prompt, it displays the result as 721
instead of the answer I want which is 28. what am I doing wrong.
hanks -Allen Thompson

<html>
<body>
<script language="javas cript">
var y=window.prompt ();
var x=y+3*7;
document.write( x);
</script>
</body>
</html>
Jul 20 '05 #1
19 2033
Allen Thompson hu kiteb:
sorry for the simple question, haven't done this in a while. when I
use the following script it keeps displaying the value of "x" like a
string. for example, if I type the number 7 in the prompt, it
displays the result as 721 instead of the answer I want which is 28.
what am I doing wrong.
hanks -Allen Thompson

<html>
<body>
<script language="javas cript">
var y=window.prompt ();
var x=y+3*7;


var x = (y * 1) + (3*7);

Unless you force js to recognise a variable as a number, half teh time
it assumes it is text, and teh + operator is both addition and
concatenation.

If I had my way, + would be reserved as addition only, and a separate
operator created for concatenation.
--
--
Fabian
Visit my website often and for long periods!
http://www.lajzar.co.uk

Jul 20 '05 #2
"Fabian" <la****@hotmail .com> writes:
var x = (y * 1) + (3*7);
Or
var x = Number(y)+3*7
or one of the other ways to convert a string into a number.

The important point is that y contains a string (prompt returns a
string), not a number, and that adding a number to a string will
always convert the number to a second string and concatenate the
strings.

<URL:http://jibbering.com/faq/#FAQ4_21>
Unless you force js to recognise a variable as a number, half teh time
it assumes it is text, and teh + operator is both addition and
concatenation.
It's not *that* bad. Javascript won't assume something half of the time.
It consistently treats strings as strings and numbers as numbers, and
when adding something to a string, it converts the other part to a string
and concatenates.

I would rather say that half of the time, you get away with forgetting
that you have a string containing a numeral, because Javascript converts
it to a number before doing arithmetic operations on it. E.g.,
var y = "42";
var x1 = y * 2; // 84
var x2 = y / 2; // 21
var x3 = y - 37; // 5
var x4 = y + 10; // 4210 - addition doesn't convert arguments to numbers.
In the first four cases, you can safely forget that y contains a string.
It's just that you can't always, so you shouldn't.
If I had my way, + would be reserved as addition only, and a separate
operator created for concatenation.


I wouldn't complain about that. I guess the behavior is stolen from Java,
where + also does concatenation on strings.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #3
> when I use the
following script it keeps displaying the value of "x" like a string. for
example, if I type the number 7 in the prompt, it displays the result as 721
instead of the answer I want which is 28. what am I doing wrong.
hanks -Allen Thompson

<html>
<body>
<script>
var y=window.prompt ();
var x=y+3*7;
document.write( x);
</script>
</body>
</html>


prompt() returns a string. Before using the '+' operator, you need to convert
the string to a number.

var x = (+y) + 3 * 7;

http://www.crockford.com/javascript/survey.html

Jul 20 '05 #4
In article <br************ @ID-174912.news.uni-berlin.de>, Fabian
<la****@hotmail .com> wrote:
Allen Thompson hu kiteb:
sorry for the simple question, haven't done this in a while. when I
use the following script it keeps displaying the value of "x" like a
string. for example, if I type the number 7 in the prompt, it
displays the result as 721 instead of the answer I want which is 28.
what am I doing wrong.
hanks -Allen Thompson

<html>
<body>
<script language="javas cript">
var y=window.prompt ();
var x=y+3*7;


var x = (y * 1) + (3*7);

<snip>

Just use var x=+y+3*7;

If the y was at the other end of the formula then
var x=3*7+(+y)

--
Dennis M. Marks
-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----== Over 100,000 Newsgroups - 19 Different Servers! =-----
Jul 20 '05 #5
JRS: In article <es************ @newsread2.news .atl.earthlink. net>, seen
in news:comp.lang. javascript, Allen Thompson <ge********@min dspring.com>
posted at Sat, 13 Dec 2003 03:12:10 :-
sorry for the simple question, haven't done this in a while. when I use the
following script it keeps displaying the value of "x" like a string. for
example, if I type the number 7 in the prompt, it displays the result as 721
instead of the answer I want which is 28. what am I doing wrong.


You basic error lies in omitting to read the newsgroup FAQ.

--
© 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.demo n.co.uk/js-index.htm> Jsc maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/Jsc/&c, FAQ topics, links.
Jul 20 '05 #6
Dennis M. Marks wrote:
If the y was at the other end of the formula then
var x=3*7+(+y)


JFTR:

var x = 3*7+ +y;

is also possible but more error-catching.
PointedEars
Jul 20 '05 #7
Douglas Crockford wrote:
prompt() returns a string.


It returns a string if the user confirms. Otherwise
it returns `null', no matter what has been typed.
PointedEars
Jul 20 '05 #8
Thomas 'PointedEars' Lahn <Po*********@we b.de> writes:
Douglas Crockford wrote:
prompt() returns a string.


It returns a string if the user confirms. Otherwise
it returns `null', no matter what has been typed.


That is browser dependent. Opera returns "undefined" , not "null".
Bot IE and Mozilla do return "null".

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #9
Waaaaay back on 13-Dec-03 11:26:28, Douglas Crockford said this about Re: why math wont work?:
following script it keeps displaying the value of "x" like a string. for
example, if I type the number 7 in the prompt, it displays the result as
721 instead of the answer I want which is 28. what am I doing wrong. hanks
-Allen Thompson

<html>
<body>
<script>
var y=window.prompt ();
var x=y+3*7;
document.write( x);
prompt() returns a string. Before using the '+' operator, you need to convert
the string to a number. var x = (+y) + 3 * 7;


That'll still give the same result, unfortunately. Whatcha need to do is this;

var x = parseInt(y)+3*7 ;

That should work.

--
da****@banana-and-louie.org * dauber.50megs.c om
* ICQ: 28677921 * YIM: dau_ber * AIM: ddaauubbeerr

Jul 20 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
19049
by: David Eppstein | last post by:
Why doesn't this work? >>> import math >>> math.exp(1j*math.pi) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: can't convert complex to float; use e.g. abs(z) The expected answer, of course, is -1.
8
2469
by: Tom | last post by:
Has anyone ever seen a IComparer for floats the returns magnitude. i.e. instead of returning -1, it would return -5. To let you know HOW different the two numbers are. obviously for int it is a - b. But for float the results would have to be normalize some how to a 32bit range. I understand there would be percision errors. Thanks Tom
17
3600
by: cwdjrxyz | last post by:
Javascript has a very small math function list. However there is no reason that this list can not be extended greatly. Speed is not an issue, unless you nest complicated calculations several levels deep. In that case you need much more ram than a PC has to store functions calculated in loops so that you do not have to recalculate every time...
6
8762
by: RobG | last post by:
I am writing a script to move an absolutely positioned element on a page by a factor using style.top & style.left. The amount to move by is always some fraction, so I was tossing up between Math.ceil/floor and parseInt +/- 1 to ensure the amount to move was at least 1 and in the right direction. I made a small test to see which one is...
5
2246
by: Ark | last post by:
Hi everyone, Does anyone know if Direct3D overloads System.Math functions? Also is it possible to access the base functions of the overloaded function (in other words restore original of the overlaoded function)? Thank you
110
8516
by: Gregory Pietsch | last post by:
I'm writing a portable implementation of the C standard library for http://www.clc-wiki.net and I was wondering if someone could check the functions in math.h for sanity/portability/whatever. I'm almost halfway through writing the over 200 functions needed to implement C99's version of math.h, and I would like to have some feedback and/or...
4
22042
by: pdlemper | last post by:
Have carefully installed Python 2.5.1 under XP in dir E:\python25 . ran set path = %path% ; E:\python25 Python interactive mode works fine for simple arithmetic . Then tried >> import math Get error Name error : name 'sqrt' is not defined Same thing with sin(x) . I'm unable to find "math" , "sqrt" , or "sin" anywhere in lib , Libs or...
2
2642
by: Helmer | last post by:
i am in programming class trying to make an applet involving random placement of colored blocks, but an error is created when i try to run it saying "no method named "random" was found in type "Math". " i have imported java.awt like so: import java.awt.*; and this is the random number statement:...
5
13523
by: aguirre.adolfo | last post by:
Hi, I am a very newbie who would very much appreciate some hints. Python 2.52. on Windows XP for now. Soon on Ubuntu 8 I am teaching myself Python following free tutorials. I can solve problems using arithmetic, but when I try to upgrade the programs using math libraries nothing seems to work. I downloaded a 2002 tutorial from Zelle "An...
0
7703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8138
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7681
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7983
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6290
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3662
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1229
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
950
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.