I am using a function where I have a readonly text input, and when I execute the function I want the number value + 1. So let's say I have 60, when I execute the function, the number returned should be 61.
But instead it's coming out 601, which is just adding the number 1 to the string. Any clue as to what is going on? Subtraction, multiplication and division all work fine. Here is a snippet
var num= $("#originalnum").val() + 1;
$("#originalnum").val(num);
And yes i've tried a few different variations, am I missing something?
A simple unary + is sufficient to turn a string into a number in this case:
var num = +$("#originalnum").val() + 1;
$("#originalnum").val(num);
The problem is that .val() returns the value of the element as a string, and when you use the + operator on a string it does string concatenation. You need to convert the value to a number first:
var num = +$("#originalnum").val() + 1; // unary plus operator
// OR
var num = Number($("#originalnum").val()) + 1; // Number()
// OR
var num= parseFloat($("#originalnum").val()) + 1; // parseFloat()
// OR
var num= parseInt($("#originalnum").val(),10) + 1; // parseInt()
Note that if you use parseInt() you must include the radix (10) as the second parameter or it will (depending on the browser) treat strings with a leading zero as octal and strings with a leading "0x" as hexadecimal. Note also that parseInt() ignores any non-numeric characters at the end of the string, including a full-stop that the user might have intended as a decimal point, so parseInt("123.45aasdf",10) returns 123. Similarly parseFloat() ignores non-numeric characters at the end of the string.
Also if it's a user-entered value you should double-check that it actually is a number and perhaps provide an error message if it isn't.
When you use the *, / or - operators JS tries to convert the string to a number automatically, so that's why those operators "work" (assuming the string can be converted).
You should use the parseInt function and make sure the value is number(use isNaN function):
var val = $("#originalnum").val();
var num = 0;
if ( !isNaN(val) )
num= parseInt(val) + 1;
Use parseInt():
var num= parseInt($("#originalnum").val(),10) + 1;
So your number is treated as an integer instead of a string (as .val() treats the result as string by default)
If you don't like the above code spelling, you can try it this way too.
$("#originalnum").val(function() {
$(this).val(parseInt($(this).val()) + 1)
});
Related
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
I have a string : "-10.456"
I want to convert it to -10.465 in decimal (using JavaScript) so that I can compare for greater than or lesser than with another decimal number.
Regards.
The parseInt function can be used to parse strings to integers and uses this format: parseInt(string, radix);
Ex: parseInt("-10.465", 10); returns -10
To parse floating point numbers, you use parseFloat, formatted like parseFloat(string)
Ex: parseFloat("-10.465"); returns -10.465
Simply pass it to the Number function:
var num = Number(str);
Here are two simple ways to do this if the variable str = "-10.123":
#1
str = str*1;
#2
str = Number(str);
Both ways now contain a JavaScript number primitive now. Hope this helps!
In javascript, you can compare mixed types. So, this works:
var x = "-10.456";
var y = 5.5;
alert(x < y) // true
alert(x > y) // false
the shortcut is this:
"-3.30" <--- the number in string form
+"-3.30" <----Add plus sign
-3.3 <----- Number in number type.
I need the two numbers to be added but somehow they are concatenated. Where am I doing it wrong?
var a;
var b;
var parsedInta;
var parsedIntb;
a=window.prompt("enter your first number");
b=window.prompt("enter your second number");
parsedInta=parseInt(a);
parsedIntb=parseInt(b);
alert("The Sum is" + parsedInta+parsedIntb);
It concatenates the result rather than addition.
You have to introduce parentheses to force the numeric addition to happen before the alert string is built:
alert("The Sum is " + (parsedInta + parsedIntb));
Without the parentheses, the + operator is naturally left-associative, so the first "addition" carried out is the string concatenation between "The Sum is" and the first value (which is treated as a string).
edit — note that the + operator prefers string concatenation over numeric addition. If either operand of + is a string, then the other operand is converted to a string and the two are concatenated.
This is beacuse the + operator is used also to do string concatenation. Since in your "The Sum is" + parsedInta+parsedIntb you are working with a string the language thinks you want to use parseinta and parseintb as strings.
You can solve by simply doing the sum before the string creation:
var sum = parseInta + parseIntb;
alert("The Sum is" + sum);
Or also by using parseInt directly in the sum line:
var sum = parseInt(a) + parseInt(b);
alert("The Sum is" + sum);
The probleme is that you are doing implicit type casting using "+" operator which will convert the number to string so your code will be like :
alert("the sum is "+number1+number2); //The number 1 will be converted to a string
,the same for the second number
So if i enter 10 in the first prompt and 10 in the second prompt the alert will show : the sum is 1010 because the first 10 is converted to a string and the second 10 will be converted to a string
But if i use parenthese like :
alert("the sum is "+(number1+number2));
Here the two number will be added and it will be coverted to a string after the addition.
P.S : don't use window object because it's a global object so you can ignore it
And sorry for my bad english i hope that you will understand
This is JavaScript. Don't expect the language to make sense.
This is because the + operator is overloaded for strings. If either of its operands is a string, + will turn the other operand into a string and concatenate them.
Since this awful operator is also left-associative, you will get
("The Sum is" + parseInta) + parsedIntb
which is a string plus a number (which is a string) plus a number, which is also a string.
Parenthesize the rightmost addition instead:
alert("The Sum is" + (parsedInta + parsedIntb));
And maybe consider starting to learn programming with a sane language.
I have the following JS immbedded in a page:
var round = Math.round;
var id = $(this).attr("id");
var len = id.length;
var indexPos = len -1; // index of the number so that we can split this up and used it as a title
var pasType = id.substring(0, indexPos); // adult, child or infant
var ind = round(id.substring(indexPos)); // converts the string index to an integer
var number = (id.substring(indexPos) + 1); // creates the number that will go in the title
window.alert(number);
id will be something like adult0, and I need to take that string and split it into adult and 0 - this part works fine.
The problem comes in when I try to increment the 0. As you can see I use Math.round to convert it to an integer, and then add 1 to it - I expect 0 to be 1 after this. However, it doesn't seem to be converting it to integer, because I get 01, not 1. When testing this with adult1 the alert I get is 11.
I'm using this question for reference, and have also tried var number += id.substring(indexPos);, which breaks the JS (unexpected identifier '+=')
Does anyone know what I'm doing wrong? Is there a better way of doing this?
The parseInt() function parses a string and returns an integer,10 is the Radix or Base
[DOC]
var number = parseInt(id.substring(indexPos) , 10 ) + 1;
This is to do with JavaScript's + in operator - if a number and a string are "added" up, the number is converted into a string:
0 + 1; //1
'0' + 1; // '01'
To solve this, use the + unary operator, or use parseInt():
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
The unary + operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt() is self-explanatory (converts into number, ignoring decimal places).
The second argument is necessary for parseInt() to use the correct base when leading 0s are placed:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
There's also parseFloat() if you need to convert decimals in strings to their numeric value - + can do that too but it behaves slightly differently: that's another story though.
Convert by Number Class:-
Eg:
var n = Number("103");
console.log(n+1)
Output: 104
Note:- Number is class. When we pass string, then constructor of Number class will convert it.
JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:
var numberAsInt = parseInt(number, 10);
// Second arg is radix, 10 is decimal.
If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.
Although parseInt is the official function to do this, you can achieve the same with this code:
number*1
The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.
Use parseInt():
var number = (parseInt(id.substring(indexPos)) + 1);` // creates the number that will go in the title
If you are sure id.substring(indexPos) is a number, you can do it like so:
var number = Number(id.substring(indexPos)) + 1;
Otherwise I suggest checking if the Number function evaluates correctly.
By this I mean NOT the default javascript behavior of string + number = string, or string + string = string. From http://www.javascriptkit.com/jsref/arithmetic_operators.shtml, the Unary plus will convert a string to a number.
So how would I specify that I want numeric addition with two strings? This seems to work, but is somewhat ugly:
var a = "5";
var b = "2";
var c = +a + +b;
Does there exist a (numeric only +) operator, that always returns a number? Can one be defined like in other languages? For examples, perhaps '%%' or '+^' or '+++'? Or is this just not possible?
No. If you want to perform numeric addition than you have to ensure that both sides of the expression are Numbers before you start.