New to Javascript calculations - javascript

I'm BRAND new to javascript so this is probably an easy fix I can't figure out.
I'm writing a easy script to calculate age Leapyear, Dog years and plus Five.
var age = prompt ("what's your age?");
var dog = age + 7;
var leapyear = age / 4;
var plusFive = age + 5;
document.write(dog, leapyear, plusFive);
JS isn't calculating age + 7. It's writing the age + 7. So if I write 15 in the age prompt it will print in the browser 157.(15) and (7) Which i understand and know why. but how do I get it to compute the math.
It's actually returning 1573.75155
thanks

Like what everyone's been saying, prompt returns a string so it needs to be converted. There are a number of ways to do this, some of which have already been mentioned:
parseInt('123')
parseFloat('123')
Number('123')
These are probably the most common and depending on context also quite possibly the most clear and intuitive ways of doing it. There are also a couple of very terse and interesting ways of converting strings to numbers, depending on which kind of number you'd like. For instance, to convert a number in a string to a float, you can prefix it with the + operator:
+'1.23'
This can seem really counter intuitive, particularly since 4 + '1.23' will actually return 41.23. So what's going on? Well, the + operator, when used as a unary operator (that is, it only has one operand on the right hand side) will always convert the operand value to a number. Compare these two (try them in a javascript console):
4 + '1.23' // returns 41.23
4 + +'1.23' // returns 5.23; the second + is a unary operator
In contrived examples such as this, it really reads rather badly so you might not want to use this trick everywhere. But in your code, it reads quite well:
var age = +prompt("What's your age?")
var dog = age + 7;
var leapyear = age / 4;
var plusFive = age + 5;
If you understand the workings of the unary plus operator (it really isn't rocket surgery) then you can get some nice terse but quite comprehensible results.
The unary + operator will always convert the value to a Number, i.e. floating point. Now, you might want an integer instead, in which case you can use the bitwise not operator twice, like so:
4 + ~~'1.23' // returns 5; note the double operator
This operator first converts the value to an integer, and then returns the bitwise complement of the value, meaning all the bits are inverted. Using it twice will mean that we get the complement's complement, i.e. the original value but this time as an integer instead of a float.
Hope this was informative!

Right now Javascript handles the input as a string, so age is a string. You're gonna want to convert that to an int using the function parseInt(age).
Official documentation
Also, I'd suggest you read this about types in JS

Use either parseInt(age) or parseFloat(age) depending on whether you want to accept non-integer ages.

Your prompt is returning your number as a string, so when you calculate 15 + 7 it's actually just concatenating "7" on to "15".
You need to convert your string to an number:
var age = prompt ("what's your age?");
age = parseInt(age,10); // Converts to an integer
// parseFloat(age) will allow fractional ages
var dog = age + 7;
var leapyear = age / 4;
var plusFive = age + 5;
document.write(dog, leapyear, plusFive);

the age is going to be treated as string so string plus int result in string you have to convert age to int :
var age= parseInt(prompt("what's your age"));
updated...

Related

Javascript: "+" sign concatenates instead of giving sum of variables

I am currently creating a site that will help me quickly answer physics questions.
As it happens, the code didn't run as expected, here is the code
if (option == "dv") {
var Vinitial = prompt("What is the Velocity Initial?")
var acceleration = prompt("what is the acceleration?")
var time = prompt("what is the time?")
Vfinal = Vinitial + acceleration * time
displayV.innerHTML = "v= vf= " + Vfinal + "ms" + sup1.sup();
}
Now, let's say Vinitial was 9, acceleration was 2, and time was 3.
When the code runs, instead of getting 15 for "Vfinal", I get 96.
I figured out that it multiplies acceleration and time fine, and then just concatenates the 9 at the beginning, with 6 (the product of 2 * 3).
I have fixed it for now by using
Vfinal = acceleration * time - (-Vinitial)
which avoids using the "+" sign, but I don't want to have to keep doing this. How do I fix it?
you are dealing with strings here, and math operations on strings will mess up. Remember when ever you are doing math operations you have to convert the data into actual numbers and then perform the math.
Use parseInt() more Details here
Your code should change to
Vfinal = parseInt(Vinitial,10) + parseInt(acceleration,10) * parseInt(time,10);
Edit 1: If the numbers are decimal values then use parseFloat() instead
So the code would be
Vfinal = parseFloat(Vinitial) + parseFloat(acceleration) * parseFloat(time);
Object-Oriented JavaScript - Second Edition: As you already know, when you use the plus sign with two numbers, this
is the arithmetic addition operation. However, if you use the plus
sign with strings, this is a string concatenation operation, and it
returns the two strings glued together:
var s1 = "web";
var s2 = "site";
s1 + s2; // website
The dual purpose of the + operator is a source of errors. Therefore,
if you intend to concatenate strings, it's always best to make sure
that all of the operands are strings. The same applies for addition;
if you intend to add numbers, make sure the operands are numbers.
You can use "+" operator with prompt() to convert returned values from string to int
var Vinitial = +prompt("What is the Velocity Initial?");
var acceleration = +prompt("what is the acceleration?");
var time = +prompt("what is the time?");
Explanation:
var a = prompt('Enter a digit');
typeof a; // "string"
typeof +a; // "number"
If you will enter non-digit data +a gives you NaN. typeof NaN is "number" too :)
You will get the same result with parseInt():
var Vinitial = parseInt(prompt("What is the Velocity Initial?"), 10);
var acceleration = parseInt(prompt("what is the acceleration?"), 10);
var time = parseInt(prompt("what is the time?"), 10);
developer.mozilla.org: parseInt(string, radix);
string: The value to parse.
radix: An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string.
Specify 10 for the decimal numeral system commonly used by humans.
Always specify this parameter to eliminate reader confusion and to
guarantee predictable behavior. Different implementations produce
different results when a radix is not specified, usually defaulting
the value to 10.
Epilogue:
Object-Oriented JavaScript - Second Edition: The safest thing to do is to always specify the radix. If you omit the radix, your code
will probably still work in 99 percent of cases (because most often
you parse decimals), but every once in a while it might cause you a
bit of hair loss while debugging some edge cases. For example, imagine
you have a form field that accepts calendar days or months and the
user types 06 or 08.
Epilogue II:
ECMAScript 5 removes the octal literal values and avoids the confusion
with parseInt() and unspecified radix.
The Problem is, Your value has been took it in a form of string .. so convert your value into Int using parseInt(accelaration).. then it will work ..
Vfinal = parseInt(Vinitial) + parseInt(acceleration) * parseInt(time)
//use ParseInt
var a=10,b=10;
var sum=parseInt(a+b);
ex:
parseInt(Vinitial + acceleration) * time

Javascript: concatenation with "," doesn't work

<button onclick="rzut()" />
<div id="wynik" />
<script type="text/javascript">
function rzut() {
document.getElementById("wynik").innerHTML = "Wynik to",Math.floor(Math.random()*6)+1;
}
</script>
For an unknown reason my script show only "Wynik to" and it skips the next part (math.floor etc)
Okay, let's go over some basics.
The first thing I would like to bring up is the concept of an Overloaded Operator. An overloaded operator, in short, is an operator that has different behaviour for different operands. An example of an overloaded operator in Javascript is +. For example:
var x = 4 + 4;
// x = 8
As you can see, adding two numeric values has the effect of summing the fields. But what about..
var x = "4" + "4";
// x = "44";
Well, because the types are strings, it behaves differently, hence it has an overloaded behaviour.
The + symbol will summate numeric values, but concatenate string values.
Bringing this forward to your example, you want to end up with a string value like..
"Wynik to,3"
Where 3 can vary. So let's look at it like this..
"Wynik to,X"
where X is some variable. Well.. this means you've got to build the string on the fly.. So following your approach (and not using some of the nice ES6 features that have been introduced), you can use our friendly overloaded + to accomplish this..
"Wynik to," + X
Where X is some random number between 1 and 6 therefore..
"Wynik to " + (Math.floor(Math.random()*6)+1);
So you'll see here, we've got a numeric value on the right hand side and a string value on the left hand side.
What Javascript does in this situation is what's known as arithmetic promotion, where all operands are promoted to the precision of the highest operand.
In this case, the right hand side of the equation is promoted to a string. Then, as we've seen above, our overloaded operator knows what to do with two strings.

Google Scripts Concatenating rather than adding

When I run my script rather than adding what I think should be two numbers, it concatenates...
I feel like I'm watching that Abbot and Costello bit. https://www.youtube.com/watch?v=9o1SAS8KyMs
var weekNum = e.parameter.weekListBox;
weekNum = weekNum + 3;
weekListBox has the values from 1 to 15.
I am trying to offset it by 3.
However 1 + 3 yields 13, not 4 as I was expecting. Drove me nuts till I realized why this was happening.
So how do I get it to add?
Thanks
It turns out, this is the only solution that worked for me... Very strange problem.
Google Spreadsheet Script getValues - Force int instead of string
Answered by hoogamaphone
You can do this easily using the unary '+' operator as follows:
First get your values from your spreadsheet using getValue() or
getValues(). Suppose you get two such values, and store them in A = 1
and B = 2. You can force them to be recognized as numbers by using any
math binary operator except for +, which concatenates strings, so A -
B = -1, while A + B will return '12'.
You can force the variables to be numbers simply by using the + unary
operator with any variable that might be interpreted as a string. For
example, +A + +B will return the correct value of 3.
The answer above explains the issue but does not provide a solution (except in comments but parseInt() is not the only/best solution).
The reason you have that issue is that the value returned by e.parameter.weekListBox; is actually a string (it is actually always the case except for dates which are date objects) so the result you get is the normal string concatenation (string+number=new string).
One simple solution is to change your code as follows :
var weekNum = Number(e.parameter.weekListBox);// make it a number
weekNum = weekNum + 3;// and the result will be a sum
See
function myFunction() {
var aa = 1;
var ab = aa + 3;
var ba = "1";
var bb = ba + 3;
}
ab = 4
but
bb = "13"

Curiosity Encountered in Javascript Tutorial

I am not understanding what the Number function does. This is the tutorial I'm using, which in fact does explain what the function does... BUT... when I delete Number it still returns the same value, so I'm not understanding its purpose. Even if I change Number to String it still returns the same value. Here is the example code:
var theNumber = Number(prompt("Pick a number", ""));
print("Your number is the square root of " +
(theNumber * theNumber));
Whats happening is its automatically converting theNumber to a number to do the *.
I am assuming you are saying you did:
var theNumber = prompt("Pick a number", "");
print("Your number is the square root of " +
(theNumber * theNumber));
Here is a good reference that explains "Automatic Conversions"
It looks like you have a second question, and is "Why would I ever use it?"
Once you have convert it you a "Number" object you now have access to some additional properties/methods which allow you to do some conversions like adding/trimming decimals, as well as converting to Exponential Notation.
Example (user Enters 1.22222222222222222222222222):
var theNumber = new Number("1.22222222222222222222222222");
theNumber.toFixed(2);
//value is now 1.22

why do I get 24 when adding 2 + 4 in javascript

I am trying this:
function add_things() {
var first = '2';
var second = '4';
alert(first + second);
}
But it gives me 24 instead of 6, what am I doing wrong?
You're concatenating two strings with the + operator. Try either:
function add_things() {
var first = 2;
var second = 4;
alert(first + second);
}
or
function add_things() {
var first = '2';
var second = '4';
alert(parseInt(first, 10) + parseInt(second, 10));
}
or
function add_things() {
var first = '2';
var second = '4';
alert(Number(first) + Number(second));
}
Note: the second is only really appropriate if you're getting strings from say a property or user input. If they're constants you're defining and you want to add them then define them as integers (as in the first example).
Also, as pointed out, octal is evil. parseInt('010') will actually come out as the number 8 (10 in octal is 8), hence specifying the radix of 10 is a good idea.
Try this:
function add_things() {
var first = 2;
var second = 4;
alert(first + second);
}
Note that I've removed the single quotes; first and second are now integers. In your original, they are strings (text).
That is one of the "Bad Parts" of JavaScript, as a loosely typed language, the addition and concatenation operator is overloaded.
JavaScript is loosely typed, but that doesn't mean that it has no data types just because a value of a variable, object properties, functions or parameters don't need to have a particular type of value assigned to it.
Basically there are three primitive data types:
boolean
number
string
null and undefined are two special cases, everything else are just variations of the object type.
JavaScript type-converts values of types into a type suitable for the context of their use (type coercion).
In your example were trying to add two objects of type string, so a concatenation occur.
You can "cast" or type convert the variables to number in many ways to avoid this problem:
var a = "2";
var b = "4";
// a and b are strings!
var sum = Number(a) + Number(b); // Number constructor.
sum = +a + +b; // Unary plus.
sum = parseInt(a, 10) + parseInt(b, 10); // parseInt.
sum = parseFloat(a) + parseFloat(b); // parseFloat.
This is I think a very common mistake, for example when reading user input from form elements, the value property of form controls is string, even if the character sequence that it contain represents a number (as in your example).
The "Bad Part" which I talk, is about the dual functionality of the + operator, overloaded to be used for both, numeric addition and string concatenation.
The operation that the + operator will do is determined completely by the context. Only if the both operands are numbers, the + operator perform addition, otherwise it will convert all of its operands to string and do concatenation.
The single quotes cause the values to be treated as characters instead of numbers. '2' + '4' = '24' in the same way that 'snarf' + 'blam' = 'snarfblam'.
You could also force the interpreter to perform arithmetic when dealing with numbers in string forms by multiplying the string by 1 (since multiplication can't be done on a string, it'll convert to a number if it can):
// fun with Javascript...
alert(first * 1 + second * 1);
But it's probably best to go with CMS's suggestion of using Number() to force the conversion, since someone will probably come along later and optimize the expression by removing the 'apparently unnecessary' multiply-by-one operations.

Categories

Resources