Concatenates instead of Addition in Javascript [duplicate] - javascript

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.

Related

Why does it show value 5150 and not 155? [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 4 years ago.
So im quite new to javascript and i tried making something simple as entering a value and add 150 to it but it wont show number + 150?
Pictures below
Code
Output
That's because you are concatenating strings. You need to convert the strings to integers by using parseInt(), and then add the numbers.
https://www.w3schools.com/jsref/jsref_parseint.asp
var fullprice = parseInt(price) + 150;
Because you're actually concatenating a string with a number. The input value is a string, so before operating with it, parse it to int with parseInt
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Javascript adding numbers as if they were a string [duplicate]

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

Addition, subtraction and multiplication of values in JavaScript [duplicate]

This question already has answers here:
Unexpected output in javascript
(5 answers)
Closed 8 years ago.
var apples = prompt('Please enter no. of apples');
var oranges = prompt('Please enter no. of oranges');
var fruits = apples + oranges;
document.write(fruits);
Why does it work with - and * and not +?
Thanks!
You're adding two strings together to get another string. That's how JavaScript does it.
Maybe what you want is numbers:
var fruits = parseInt(apples, 10) + parseInt(oranges, 10);
As a note, using prompt to collect information is utterly barbaric. What you need to do is have two input boxes and a submit trigger that does the math, or since it's so trivial, hook it up to trigger on any change to either value. jQuery basics here.
You're doing string concatenation with the + instead of an addition.
Parse to float or int.
var fruits = parseFloat(apples) + parseFloat(oranages);
prompt returns a string, thus it's appending the strings together.
Javascript will convert to an int when you try other operators on the variables.
Use parseInt to make sure they're ints.

Strange if-statement evaluation behavior [duplicate]

This question already has answers here:
Javascript string/integer comparisons
(9 answers)
Closed 7 years ago.
My javascript is behaving very strange!
I have a input field in my html file. This input field is read by javascript in the following way:
var bscore = $("#bscore").val();
Then i want to show an alert if the input is below a certain input
if(bscore<"913"){
document.getElementById("bscorealert").style.display="block";
};
This works fine. So when the number is above 913 it should not show. Only javascript is behaving very strange, when the number in the bscore input field is above 999 (so 1000 and higher) the if statement is triggered and the alert is shown.
How is this possible?
It's possible because you are comparing strings, not integers. String comparison is lexicographical, so "9" > "10" and so on.
You will want to convert before comparing with Number(strValue) or with the unary operator +:
var bscore = +$("#bscore").val(); // + prefix converts to number
if (bscore < 913) ... // no quotes around 913!
You're trying to compare 2 strings, which uses the alphabetical comparison. If you enter a value between 9130 and 9999 in the field, you'll notice that the messagebox doesn't show as well.
You'll have to do a parseInt to compare numerical values.

Effect of x = +x in JavaScript [duplicate]

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?

Categories