How to make 1 + 1 = 2 instead of 1 + 1 = 11 [duplicate] - javascript

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 7 years ago.
I am trying to add the number mathematically, but it keeps adding the number after it.
It takes the id number (begen), then it gets the number inside another div (kacbegen).
var begen = $(this).attr('id');
var kacbegen = $("#math" + begen).text();
var toplam = (kacbegen + 1);
alert(toplam);
However, when doing the math (toplam), it alerts all the numbers.How to add the number mathematically ?

Convert it to number via adding a +:
var toplam = (+kacbegen + 1);
Unary plus (+)
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.

It looks like you're working with Strings (and thus a + b is the concatenation operator) when you want to be working with Number (so x + y would be addition)
Perform your favorite way to cast String to Number, e.g. a unary +x
var kacbegen = +$("#math" + begen).text();

You need to use parseInt to convert kacbegen, which is a String instance, to a Number:
var begen = $(this).attr('id');
var kacbegen = $("#math" + begen).text();
var toplam = (parseInt(kacbegen) + 1);
alert(toplam);
The + operator, when used with a String on either side, will serve as a concatenation, calling Number.prototype.toString on 1.

You need to cast the contents to a number:
var contents = $("#math" + begen).text();
var kacbegen = parseFloat(contents);

You use kacbegen as a string. Please use as a integer use parseInt(kacbegen) + 1

Related

jQuery object - Value = value + number - Doesn't work?

I'm attempting to update a value in an object and set it to the current value + another number. So for instance, if an object's value is 5, I want it to update like this: object key : current value (5) + 7
container[response["id"]]["quantity"] += quantity;
console.log(container[response["id"]].attr("quantity"));
This is what I'm currently attempting.. I end up with 57 instead of 12.
Any ideas?
You get as a string and + with strings concatenate them. First parse to the number using parseInt() or parseFloat() than add.
let number = parseInt(container[response["id"]]["quantity"]);
number += quantity;
container[response["id"]]["quantity"] = number;
The issue is, the value return by response["id"]]["quantity"] is a string. And when you try to add a number using + to a string, then it will concatenate it, something like 5 + 7 is 57. To deal with this, you have to parse the number to Int or to Float by using parseInt() or parseFloat(). Ex:
let num = parseInt(container[response["id"]]["quantity"]);
num += quantity;
container[response["id"]]["quantity"] = num;

JavaScript input value issue [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 8 years ago.
The following doesn't work as expected:
function sum(x,y){
return x + y;
}
document.getElementById('submit').onclick = function(e)
{
//do someting
e.stopPropagation();
var value1 = document.getElementById('v1').value,
value2 = document.getElementById('v2').value;
var newSum = sum(value1, value2);
console.log(newSum);
}
There is something wrong with the values being picked up. It should return the sum and not "1+2=12"
Change
return x + y;
to
return parseInt(x) + parseInt(y);
You have to convert the values to numbers first, before adding them. If the numbers are floats, you can use parseFloat instead of parseInt.
Edit As suggested by RGraham in the comments, its always better to pass the radix (check parseInt's doc) explicitly. So, the code becomes
return parseInt(x, 10) + parseInt(y, 10);
For more accuracy:
function sum(x,y){
return parseFloat(x) + parseFloat(y);
}
You need to parse your value to an int as all values are passed as string in javascript.
value1 = parseInt(document.getElementById('v1').value, 10);
value2 = parseInt(document.getElementById('v2').value, 10);
use
parseInt
Syntax
var num = parseInt(string, radix);
Parameters
string
The value to parse. If string is not a string, then it is converted to one. Leading whitespace in the string is ignored.
radix
An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
function sum(x,y){
return parseInt(x,10) + parseInt(y,10);
}

add together 2 int vars with javascript

I'm working on a send / resend email button for the backend of my website and currently am trying to work out how to add 2 integers that I have made vars.
The script works fine as long as the integers are not 0, could anyone give me some pointers? I need it to show the total regardless of whether 1 of the vars is 0, thanks in advance
function sendResend() {
var selected = Array();
var selectedSend = $(".no:checked").length;
var selectedResend = $(".yes:checked").length;
var totalSendResend = parseInt(selectedSend) + parseInt(selectedSend);
$('input:checked').each(function () {
selected.push($(this).attr('name'));
});
var answer = confirm('You have selected ' + totalSendResend + ' emails. ' + selectedSend + ' New emails will be sent & ' + selectedResend + ' will be resent. Are you sure you want to continue?');
if (answer) {
alert(selected);
}
}
You have a typo in your code:
var totalSendResend = parseInt(selectedSend) + parseInt(selectedSend);
That adds the same values together; you wanted this:
var totalSendResend = selectedSend + selectedResend;
You didn't need the parseInt() cast at all, but if you did, you should always specify the radix as the second parameter, e.g. parseInt('0123', 10)
When you call ParseInt(myvalue) and myvalue begins with 0, it returns you an int considering value is expressed in octal.
To avoid this behavior always use parseInt(value, 10);
Edit : More info on how parseInt works no radix is specified :
If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
If the input string begins with any other value, the radix is 10 (decimal).
See more here

How can I add a number to a variable to which I assigned a number in Javascript?

I have the following:
var offset;
offset = localStorage.getItem('test.MenuList.Offset.' + examID + "." + level) || 0;
offset += 100;
When I use the debugger this offset now has 0100. I want it to add like a number not a string. How can I do this?
Please note I changed the question slightly because I realized I was getting the value from local storage. I assume this returns a string. But I am still not sure how to solve this.
The code you gave won't do that. I assume your value in your actual code is a numeric string. If so, the + will behave as a string concatenation operator, so you must convert the value to a number before using +.
You can do that with parseFloat().
var offset = localStorage.getItem('test.MenuList.Offset.' + examID + "." + level);
offset = parseFloat(offset) || 0;
Or in most cases, you can simply use the unary version of + to do the conversion.
offset = +offset || 0;

Value keeps adding as string in Javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Addition turns into concatenation
Here's what I have...
var srate = Math.round(princ * intr * term * 100) / 100; //works fine
var dasvalue = princ + srate; //doesn't work
document.calc.pay.value = dasvalue;
The "var dasvalue = princ + srate;" adds the two sums up as strings.
100 + 1.4 = 1001.4
What am I doing wrong?
You can use the unary plus operator to cast to type Number, ensuring addition rather than concatenation:
var dasvalue = +princ + +srate;
princ is a string too. You can convert it to a Number with the unary + operator.
If your value in princ comes from an input you need to convert it into a number first.
var dasvalue = Number(princ) + srate;

Categories