This question already has answers here:
Coerce to number
(4 answers)
Closed 9 years ago.
Going though the asm.js documentation I've observed this strange (to me at least, quite new to JS) snippet all over the sample code:
function test(x) {
x = +x; // THIS
...
return +(x*y);
}
What is the purpose of the + on the first line?
Its simply used for casting a value with another type to number. Additonally it will return NaN if the value after that + symbol could not get converted into a number.
FIDDLE
From the book Javascript and Jquery - The Missing Maunal
var numOfShoes = '2';
var numOfSocks = 4;
var totalItems = +numOfShoes + numOfSocks;
Adding a + sign before a variable (make sure there’s no space between the two) tells
the JavaScript interpreter to try to convert the string to a number value—if the string
only contains numbers like “2”, you’ll end up with the string converted to a number.
In this example, you end up with 6 (2 + 4). Another technique is to use the Number()
command like this:
var numOfShoes = '2';
var numOfSocks = 4;
var totalItems = Number(numOfShoes) + numOfSocks;
Number() converts a string to a number if possible. (If the string is just letters and not
numbers, you get the NaN value to indicate that you can’t turn letters into a number.)
Perhaps I am reading this wrong but from the specs http://asmjs.org/spec/latest/#parameter-type-annotations
is that casting it as a double?
Related
This question already has answers here:
Javascript ++ vs +=1
(3 answers)
Closed 5 years ago.
I was going through exercise problem from Stoyan stefanov book named Object oriented Javascript.
Problem :
var s = 'ls';
s++;
When I execute this in chrome, I get NaN.
For the same code above if I do
var s = 'ls';
s = s+1;
I get output as ls1
Can anyone please explain the reason behind it?
++ tries to convert x as number first. Hence failed because x is having string value and return NaN.
When you do ++ its attempting to increment a number. When you use the + sign, it's either adding or concatenating. Its "smart" and see's that s is a string, so it concatenates it with 1. With ++, you can't increment a string so you get NaN (Not a number)
s++ is an increment operation which is commonly performed for numbers hence the output nan( not a number). In the second case you are doing a concatenation operation. So the ‘ls’ + 1 gives ‘ls1’.
You can't increment strings via ++. That operator is reserved exclusively for the number primitive. Instead Try:
var s = 'ls';
s += 1;
console.log(s);
The above is syntactic sugar for what you originally posted (string concatenation):
s = s + 1;
This question already has answers here:
Why does JavaScript handle the plus and minus operators between strings and numbers differently?
(7 answers)
Closed 5 years ago.
Why does Javascript give an output of 0 when I use the odd operator?
What is the difference between subtraction and addition with a string?
var x = 1;
console.log(x+'1') // Outputs 11
console.log(x-'1') // Outputs 0 -- but why?
So how can I do mathematical calculations?
The + operator has one of two three meanings in javascript. The first is to add numbers, the second is to concatenate strings. When you do 1 + '1' or '1' + 1 the operator will convert one operand that is not a string to a string first, because one other operand is already evaluated to be a string. The - operator on the other hand has just one purpose, which is to subtract the right operand from the left operand. This is a math operation, and so the JS engine will try to convert both operands to numbers, if they are of any other datatype.
I'm not sure though why typecasting to strings appears to have precedence over typecasting to numbers, but it obviously does.
(It seems to me the most likely that this is a pure specification decision rather than the result of other language mechanics.)
If you want to make sure that the + operator acts as an addition operator, you can explicitly cast values to a number first. Although javascript does not technically distinguish between integers and floats, two functions exist to convert other datatypes to their number equivalents: parseInt() and parseFloat() respectively:
const x = 10;
const result = x + parseInt('1'); // 11
const y = 5;
const result2 = y + parseFloat('1.5'); // 6.5
const result3 = y + parseInt('1.5'); // 6
Edit
As jcaron states in the comment below, the + operator has a third meaning in the form of an unary + operator. If + only has a right operand, it will try to convert its value to a number almost equivalent as how parseFloat does it:
+ '1'; // returns 1
+ '1.5'; // returns 1.5
// In the context of the previous example:
const y = 5;
const result2 = y + +'1.5'; // 6.5
Dhe difference with parseFloat is that parseFloat will create a substring of the source string to the point where that substring would become an invalid numeric, whereas unary + will always take the entire string as its input:
parseFloat('1.5no-longer-valid'); // 1.5
+ '1.5no-longer-valid'; // NaN
That is because + is a concatenation operator. So javascript considers it to be a concatenation operator rather than a mathematical operator.But it is not the case with / ,* ,/ etc.
This happens because + its also used to concatenate strings. Then, JS always will find the better way to make the correct typecasts basing on types. In this case, the x+'1' operation, will be identified as string type + string type.
Otherwise, x-'1', will become int type - int type.
If you want to work with specific types, try to use type cast conversions, link here.
This question already has answers here:
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 6 years ago.
I have been playing around with cookies for the first time, and I have saving part of it completed. The data I'm saving are numbers and the most important part of these nubers is that I can add, subtract and so on with these. However when I try to add a number to one of my saved parametres it adds them as if they were text.
Example:
I have a cookie called value, and when I want this value I use a script I found by Jeffery To that looks like this:
function readCookie(name) {
return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];
}
After I have collected this cookie I want to add one to it. Lets say that value equals nine, when it should look like this: value + 1 = 10. Simple math. However it gives me this 91. Why does it do this? I know that it is because it thinks the numbers are a string of text, but how can I get this to behave like numbers?
Solution
After reading the comments I learned that i needed to put my value inside a parseInt(). So i simply modified the funtion to say:
function readCookie(name) {
return parseInt((name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1]);
}
The + operator in JavaScript can mean mathematical addition or string concatenation. The one you get is based on the implicit type of the operands. If one of the operands is a string, the other will be converted to a string and you'll get concatenation.
The trick is to do the math on the numbers first (you can surround the math portion with parenthesis or do the math in a separate statement) and then inject the result into your string.
To force a string containing a number character into a number, you can use parseInt() and parseFloat():
var result = parseInt(value, 10) + 1;
Note that with parseInt(), you should supply the optional second argument, which specifies the radix for the operation. If the first argument happens to refer to a string that contains a hex value, the result will be based on hex, not base 10. That's why 10 is used in my example.
Also note that both parseInt() and parseFloat() stop after finding the first non-valid characters that can't be treated as numbers. So, in a string like this: "Scott7Marcy9", you would get NaN.
Cookies are saved as string values as you guessed. To get your desired effect, you're going to need to parse your value. If you are absolutely sure it will be an integer, use:
parseInt(value) + 1
This question already has answers here:
Javascript concatenating numbers, not adding up
(3 answers)
Closed 7 years ago.
var tt = gas+0.1
document.write (vartt);
Duplicate
You could make use of Number function too.
var tt = Number(gas) + 0.1;
document.write(tt);
The user entered a string. If you want to do arithmetic with it instead of string concatenation, you must convert to a number. There are many different ways to do that including parseInt(gas, 10), parseFloat(gas), Number(gas) and +gas:
Here's one implementation:
var tt = parseFloat(gas) + 0.1;
document.write(tt);
Also, your document.write() statement was not correct either. The variable name is just tt, not vartt.
Unless you are using <input type="number" /> for the input, the user provided data will be a string. By default, when you try to add a string + a number it will cast that number to a string. You can do what Видул Петров suggested and add the unary + to gas to force cast it to a number, however if it's still a string that can't be cast to a number (like someone entering in the word 'five' vs '5'), youll get NaN as a result unless you have the proper control over the incoming data.
This question already has answers here:
javascript calculation formula is not working
(2 answers)
Closed 10 years ago.
So here is a dorky experiment I put together basically trying to generate a D&D style attack roll with a modifier. I want to add the numbers, but javascript keeps adding the numbers as strings. I'm not sure how to get the basic math done..... Here is my code-
function battle()
{
var CS = document.battleForm.playerCS.value;
var D20 = Math.ceil(Math.round(Math.random() * 20))
var attackRoll = CS + D20
if (isNaN(CS))
{
alert ("please provide your Combat Score!")
return
}
if (CS != '')
{
document.battleForm.enemyCS.value = attackRoll
}
}
To ensure two numbers are added together, try:
var num3 = +num1 + (+num2);
This could be preferred over the use of parseInt or parseFloat for two reasons:
+ will convert any number (meaning, you don't need a different method for an integer and a float)
+ will fail if either value are not convertible. parseInt and parseFloat ignore any trailing text in the variable. So for example, parseInt("10px", 10) results in 10, while (+"10px") results in NaN.
It's up to you what you want to use.
var CS = parseInt(document.battleForm.playerCS.value, 10); // or parseFloat if you expect float number
The value of any form text is a string, so you need to convert it to number.