Google Scripts Concatenating rather than adding - javascript

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"

Related

How to get an 8 decimal output?

I am trying to get an 8 decimal output from the following function.
The following function multiplies an input by 2 and then updates this input with the wagerUpdate variable. I would like this outputted number to have 8 decimal places.
For example: if input number is 0.00000001 (this code is for a bitcoin website), then I would like output number to be 0.00000002. For some reason the code below is not working properly as the output number is in the format of 2e-8 without the .toFixed(8) code. Please help if you are able to. Thank you so much.
<script>
function MultiplyWagerFunction() {
var wager = document.getElementById("wagerInputBox").value;
var wagerUpdate = wager*2;
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
}
</script>
If you remove the + before wagerUpdate.toFixed(8) it should work fine. wagerUpdate has already be converted to a number when you multiplied it by 2 so there should be no need for the unary +
var a = "0.00000001";
var b = a*2;
console.log(b.toFixed(8));
console.log(+b.toFixed(8));
^ see the difference.
The reason it doesn't work is because what you are doing is equivalent to:
+(b.toFixed(8))
because of the precedence of the operators (member access . is higher than unary +). You are converting b to a string with .toFixed and then converting it back into a number with + and then converting it back into a string again! (this time with the default toString behavior for numbers giving you exponential notation)
Just remove + from +wagerUpdate.toFixed(8); and you would be good.
Instead of:
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
try:
document.getElementById("wagerInputBox").innerHTML = +wagerUpdate.toFixed(8);
Why I say so is may be when you set value, browser tries to convert to best possible outcome. But, inner HTML should take the string equivalent!

what is the output of console.log(+32)?

Does javascript skips "+" symbol for certain functions?
Please find the below code
console.log(+32)
Why do we get the output from console as 32?
+ will try parse your variable/value into the number.
So if you want to get +32 in the console, you need to work with strings.
See an example
In the first case variables are concatenated, because one of them is a string.
In the second case, I first parse a into the number with + operator and get the sum of two numbers.
var a = '1';
var b = 2;
console.log(a + b);
console.log( (+a) + b);

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

New to Javascript calculations

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...

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