javascript (+) sign concatenates instead of giving sum? [duplicate] - javascript

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 5 months ago.
I created a simple program that make the sum of two numbers BUT..
the program is concatenating instead, This is so confusing!
Can anyone help?
function calculate() {
var numberOne = document.querySelector(".first").value;
var numberTwo = document.querySelector(".second").value;
var sum = numberOne + numberTwo;
document.querySelector(".result").innerHTML = "The sum of the two numbers is : " + sum;
}
<!doctype html>
<html>
<body>
<p>Calculate sum of two numbers !</p>
Enter 1rst Number:<br>
<input type="number" class="first" placeholder=""><br><br> Enter 2nd Number:<br>
<input type="number" class="second" placeholder=""><br><br>
<input type="button" onclick="calculate()" value="calculate">
<p class="result"></p>
</body>
</html>

Here value gives you a string, hence the concatenation. Try parsing it as an Number instead:
var sum = parseInt(numberOne) + parseInt(numberTwo);
See the demo fiddle.

Javascript takes dom elements as string only by default. To make mathematical calculation, you need to typecast it to integer/float or convert to number.
parseInt(number) = number, truncates after decimal value
parseFloat(number) = number with decimal values
Number(number) = number with or without decimal

Your numberOne and numberTwo are strings, so you get concatenated strings when use + sign with two string.
Parse first to numbers then sum them. You can use parseInt() and parseFloat() functions for it.
var numberOne = '7';
var numberTwo = '8';
var sum = numberOne + numberTwo;
console.log(sum);
sum = parseFloat(numberOne) + parseFloat(numberTwo);
console.log(sum);

Use parseInt() for this, Check snippet below
function calculate() {
var numberOne = document.querySelector(".first").value;
var numberTwo = document.querySelector(".second").value;
var sum = parseInt(numberOne) + parseInt(numberTwo);
document.querySelector(".result").innerHTML = "The sum of the two numbers is : " + sum;
}
<p>Calculate sum of two numbers !</p>
Enter 1rst Number:<br>
<input type="number" class="first" placeholder=""><br><br>
Enter 2nd Number:<br>
<input type="number" class="second" placeholder=""><br><br>
<input type="button" onclick="calculate()" value="calculate">
<p class="result"></p>

Example , you can use this:
var numberOne:number = +document.querySelector(".first").value;
var numberTwo:number = +document.querySelector(".second").value;
var sum = numberOne + numberTwo;
You should use + Angular typeScript

It's just because value returns with string. So sum operation ends with concatenation.
you need to convert both those values.
user below code
var sum = parseFloat(numberOne) + parseFloat(numberTwo);

Who are using javascript in salesforce make sure
var a= 8 ;
var b =8 ;
var c = a+b;
This will give u result output = 88;
It is will just concatenate. If you want to add those two:
You should write logic as :
var a = 8;
var b = 8
var c = parseInt(a)+ parseInt(b);
This will give you the desired result of 16 , The same is the case with multiplication.
Hope this helps.

Related

How to use .toFixed() from an input field

I can't seem to understand why I can't get .toFixed() to work in my code. I've tried different variations but something is missing.
I get the following error upon running the code.
Uncaught TypeError: document.getElementById(...).value.toFixed is not
a function
My Code:
<input type="number" id="num1">
<p>+</p>
<input type="number" id="num2">
<p>=</p>
<p id="result"></p>
<br>
<button id="submit" onclick="calculate()">Calculate</button>
<script>
function calculate(){
const a = document.getElementById("num1").value;
const b = document.getElementById("num2").value;
let finalAnswer = a.toFixed(2) + b.toFixed(2);
document.getElementById("result").innerHTML = finalAnswer;
console.log(a);
}
</script>
toFixed is defined in Number as you can see in the documentation therefore you must first convert the input values to numbers before using it.
For that you can use the Number constructor passing it the text to convert:
let myNumber = Number(someString);
After that you can output the result with toFixed() which gives you a string with as many digits after the decimal point as the number you passed to it:
console.log(myNumber.toFixed(2));
Taking all of this into consideration you can change your code to:
function calculate() {
const a = document.getElementById("num1").value;
const b = document.getElementById("num2").value;
//Convert both inputs to Number's before adding them
let finalAnswer = Number(a) + Number(b);
//toFixed only here when you need to output it
document.getElementById("result").innerHTML = finalAnswer.toFixed(2);
console.log(a);
}
<input type="number" id="num1">
<p>+</p>
<input type="number" id="num2">
<p>=</p>
<p id="result"></p>
<br>
<button id="submit" onclick="calculate()">Calculate</button>
The .toFixed() is a method for numbers. When you get the value from a input, it is a string. Therefore you have to convert it to a number.
You can convert to number with:
Number()
So, your code should look something like this:
const a = Number(document.getElementById("num1").value); const b = Number(document.getElementById("num2").value);
That's because your input gets evaluated as a string and not as a number, this is one of the multiple ways i'd solve it:
const a = document.getElementById("num1").value - 0;
const b = document.getElementById("num2").value - 0;
Hi you can use step for float range ether.You cant use:
<input type="number" step=any
To float I recomend to setting 0.01.

Adding 1 incrementally to a string with numbers

$("#next").click(function() {
var text = $("#textbox").val();
var Numbers = text.substring(4, 8); //To get the 4 numbers
var Num = parseInt(Numbers, 10); //To convert to an integer?
var Add = +(Num).val() + 1; //Increment 1?
$("#textbox").val(Add); //Output final value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="next" value="Increment" />
<br/>
<input type="text" id="textbox" value="ABC-123" />
I have a text box with a string of "ABC-1234" as the value and a button. I'm trying to add 1 to what's entered in the text box every time I click the button. I'm fairly new to programming but this is what I've come up with, which ends with the result of NaN.
The problem you want to solve is to add one to the numeric part of a mixed alpha-then-numeric text string.
Assuming your text will contain an alpha part, then a literal dash -, and finally a numeric part, it is easy to extract the numeric part using the String.split() method.
var text = $("#textbox").val();
var parts = text.split('-');
Now parts[0] is everything to the left of the dash and parts[1] is everything to the right. Just parse that into a number, add one, and add it back with the rest of the text, placing it back in the field.
$("#next").click(function() {
var text = $("#textbox").val();
var parts = text.split('-'); // Get the numbers in parts[1]
var num = parseInt(parts[1], 10); // Convert to an integer
num++; //Increment 1?
$("#textbox").val(parts[0] + '-' + num); //Output final value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="next" value="Increment" />
<br/>
<input type="text" id="textbox" value="ABC-123" />
This is more flexible than text.substring(4, 8); because it will work with any length string and any length number, as long as there is a dash between them.
your code is almost right, but you have to change a few things to make it "right":
in dependency of the naming convention of javascript write the variables in lower(Camel)Case.
parseInt returns a primitive type of number. There is need for calling val() method on it! There is no function like that. Just use the variable itself
you have to prepend your increased number with the letters you chop of at the beginning.
All in all:
$("#next").click(function(){
var text = $("#textbox").val();
var numbers = text.substring(4); //To get all the numbers
var num = parseInt(numbers, 10); //To convert to an integer?
num = num + 1; //Increment 1?
$("#textbox").val(text.substring(0,4)+num); //Output final value
});

Add two numbers in JavaScript function

I am a beginner in JavaScript. Our teacher asked us to write a program to add two numbers using function add(). The question is shown as follows.
However, when I use my code to add the two numbers. The result is not a number.
<html>
<head> <title> Third example </title>
<script type="text/javascript">
function sum (x,y)
{ num1=parseInt(x);
num2=parseInt(y);
return (num1+num2);}
var input1 = window.prompt("Enter a number: ", 0);
var input2 = window.prompt("Enter another number: ", 0);
var input3 = window.prompt("Enter another number: ", 0);
var value1 = parseFloat(input1 + input2);
var value3 = parseFloat(input3);
var sum = sum(value1 + value3);
document.writeln("<h1> First number: " + value1 + "</h1>");
document.writeln("<h1> Second number: " + value3 + "</h1>");
document.writeln("<h1> Sum: " + sum + "</h1>");
</script>
<head>
<body></body> </html>
Why the sum is not a number?
You have to add parseFloat() separately for input1 and input2 when you calculate the sum for value1. Another change is the var sum = sum1(value1 , value3); instead of var sum = sum1(value1 + value3); which makes the parameter y of sum(x,y) as undefined.
var input1 = window.prompt("Enter a number: ", 0);
var input2 = window.prompt("Enter another number: ", 0);
var input3 = window.prompt("Enter another number: ", 0);
var value1 = parseFloat(input1) + parseFloat(input2);
var value3 = parseFloat(input3);
var sum = sum1(value1 , value3);
document.writeln("<h1> First number: " + value1 + "</h1>");
document.writeln("<h1> Second number: " + value3 + "</h1>");
document.writeln("<h1> Sum: " + sum + "</h1>");
function sum1 (x,y)
{
return (x+y);
}
Also, as Adriani6 mentioned you don't need to parseFloat again inside sum1 as you assign a parsed float already to value1 and value3
Although a bit dirty, this works:
var amount = 58.02;
var total = '£' + (amount*1 + 177);
...gives the the expected answer of £217.73
Enclosing within brackets forces 'amount' to be a number. However...
var amount = 40.73;
var total = '£' + (amount*1 + 177.82);
gives a really silly answer of £218.54999999999998 (!)
[ Edited 26th January - following part in italics kept for reference...
This is only true if the (correct) decimal part of the answer is .55 or .65 Bug in Javascript???? (It's the same in Firefox and Chrome.)
So some more manipulation is required to be absolutely certain: multiplication, integerising and subsequent division by 100...
var amount = 40.73;
document.write('Total is: £' + parseInt(amount*100 + 17782) / 100);
.. gives the correct answer of 'Total is: £218.55' ]
Edit: Better solution found later uses toFixed() :-
var amount = 40.73;
var total = 'Total is: £' + (amount* + 177.82).toFixed(2);
.. also gives the correct answer of 'Total is: £218.55'
Soooooo -
1) You need to enclose the numbers you want to add within brackets if the sum will be part of a string;
2) Multiplying each 'number' by one forces the result to be a number - so (input1*1 + input2*1) is forced to be the arithmetic sum. This is necessary in the original questioner's script, but multiplying by one isn't needed in my example;
3) To ensure you don't get a silly answer, append .toFixed(n) to the bracketed expression - where n is the number of decimal places.
Utterly tedious (still)....
(and) Much better to use PHP if you can!
The error you're seeing is here:
sum(value1 + value3)
Your sum function expects the arguments separately and will internally perform the addition, but you're adding them in-line before sending them to the function. Since only one value is sent to sum(), its second argument is undefined and therefore "not a number". Simply separate the values:
sum(value1, value3)
The other error that you may not have noticed yet is here:
parseFloat(input1 + input2)
If you enter 1 and 2 for example, the result of this will be 12. This is because you're "adding" (concatenating) the strings before converting them to a numeric value. Convert them first, then add them. Something like this:
var value1 = parseFloat(input1) + parseFloat(input2);
Aside from that the code can probably be cleaned up a bit more, such as not needing all of the parsing you're doing. (Once something is parsed to a numeric value, it doesn't need to be parsed to a numeric value again.) You'd also do well to look into setting values to elements on the page instead of using things like document.writeln(), but that could be a lesson for another day.
Because in Javascript, the + operator is overloaded, i.e., has multiple meanings depending on the arguments you give it. The + means concatenation for strings and addition for "numbers" (for different types of numbers).
You can use an add function that takes and ads as many parameters as you need:
function add() {
// Create an array from the functions arguments object
// then sum the array members using reduce
var sum = Array.from(arguments).reduce(function(a, b) {
return a + b;
});
console.log(sum);
}
// You can now add as many numbers as you like
// just by passing them to the function
add(2, 5);
add(2, 3, 5);

JavaScript parseInt incorrect conversion

Consider:
<html>
<body>
<input Id="1"></input>
<input Id="2"></input>
<button Id="3"onclick="add()">Add</button>
<script>
function add()
{
var num1 = document.getElementById("1").value;
var val1 = parseInt(num1);
var num2 = document.getElementById("2").value
var val2 = parseInt(num2);
var val3 = val1 + val2;
var x = +num1 + +num2;
alert(val3);
</script>
</body>
</html>
I want to add two numbers in JavaScript. But when I am providing '11111111111111111' to a textbox, parseInt is converting it into 11111111111111112 instead of 11111111111111111. Why is it doing this?
I have tried all techniques. I first converted var to string and parsed it into int then added, used different radix with parseInt, but I still get nothing.
I also noted that when I am providing 16 1's to it, it's working fine, but with 17 1's it's doing this.
JavaScript numbers are IEEE 754 doubles which have 15-17 significant digits precision.
In your case the 11111111111111111 number has 17 digits which causes the observed issues.

Addition operation issues?

Hi i'm trying to do simple addition of two numbers in javascript. When i'm trying to get the two input element values, the result is coming in a concatenation of two numbers
Here is the code:
<html>
<title>
</title>
<head>
<script type="text/javascript">
function loggedUser() {
//Get GUID of logged user
//alert('success');
var x, y , result;
x = document.getElementById('value1').value;
y = document.getElementById('value2').value;
result=x+y;
alert(result);
document.getElementById('res').value = result;
}
</script>
</head>
<body>
<input type="text" id="value1"><br>
<input type="text" id="value2"><br>
<input type="text" id="res">
<input type="submit" value ="submit" onclick=loggedUser();>
</body>
</html>
The "+" operator is overloaded. If any of the parameters is a string, they are all converted to strings and concatenated. If the parameters are numbers, then addition is done. Form control values are always strings.
Convert the parameters to numbers first using one of the following:
x = Number(document.getElementById('value1').value);
or
x = parseInt(document.getElementById('value1').value, 10);
or
x = parsefloat(document.getElementById('value1').value);
or
x = +document.getElementById('value1').value;
or
x = document.getElementById('value1').value * 1;
and so on...
Oh, you can also convert it only when necessary:
result = Number(x) + Number(y);
etc.
The input fields contain strings. If you want to sum two numbers, you have to convert the strings to numbers before adding - otherwise you are just adding two strings. There are lots of ways to do that depending upon what you want to allow. Here's one:
var x, y , result;
x = Number(document.getElementById('value1').value);
y = Number(document.getElementById('value2').value);
result=x+y;
alert(result);
document.getElementById('res').value = result;
See it working here: http://jsfiddle.net/jfriend00/BWW2R/
document.getElementById('').value returns a string. You need to call parseInt on that to make it a number.
It's because x and y are actually strings, not numbers. The value field of the element is always a string, so x+y gives you the concatenation of x and y.
You can parse x and y as integers and add the result of the parsing: that will give you what you want.
The problem is when you take those values you are getting a string and in result you are doing a concatenation. You should use parseInt on both x and y like this:
x = parseInt(document.getElementById('value1').value);
y = parseInt(document.getElementById('value2').value);

Categories