This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
How can I force these strings to be treated as numbers?
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
(+varname)
So, in your case it's:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
convert the strings to floats with parseFloat(string) or to integers with parseInt(string)
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
You can use this to add numbers:
var x = +num1 + +num2;
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
http://www.crockford.com/
http://javascript.crockford.com/
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
I've always just subtracted zero.
num1-0 + num2-0;
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
Here, you have two options to do this :-
1.You can use the unary plus to convert string number into integer.
2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
Using parsing approach-
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
You can use parseInt to parse a string to a number. To be on the safe side of things, always pass 10 as the second argument to parse in base 10.
num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);
Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.
For example
5 - 7.6 = -2.5999999999999996
#cr05s19xx suggested on a duplicate question:
JavaScript is a bit funny when it comes to numbers and addition.
Giving the following
'20' - '30' = 10; // returns 10 as a number
'20' + '30' = '2030'; // Returns them as a string
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
Use the parseFloat method to parse the strings into floating point numbers:
parseFloat(num1) + parseFloat(num2)
I use this in my project.I use + sign to treat string as a number (in with_interesst variable)
<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest = PHP"+with_interesst;
}
</script>
<div name="printchatbox" id="printchatbox">
<form id="Calculate" class="form-horizontal">
<h2>You Can Use This Calculator Before Submit </h2>
<p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
<option value="40">40 Days</option>
<option value="50">50 Days</option>
<option value="60">60 Days</option>
<option value="70">70 Days</option>
<option value="80">80 Days</option>
<option value="90">90 Days</option>
<option value="100">100 Days</option>
<option value="120">120 Days</option>
</select>
</p>
<h2 id="payment"></h2>
<h2 id ="with_interesst"></h2>
</form>
</div>
Hope it helps
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
You may use like this:
var num1 = '20',
num2 = '30.5';
alert((num1*1) + (num2*1)); //result 50.5
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html
Related
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
How can I force these strings to be treated as numbers?
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
(+varname)
So, in your case it's:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
convert the strings to floats with parseFloat(string) or to integers with parseInt(string)
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
You can use this to add numbers:
var x = +num1 + +num2;
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
http://www.crockford.com/
http://javascript.crockford.com/
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
I've always just subtracted zero.
num1-0 + num2-0;
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
Here, you have two options to do this :-
1.You can use the unary plus to convert string number into integer.
2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
Using parsing approach-
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
You can use parseInt to parse a string to a number. To be on the safe side of things, always pass 10 as the second argument to parse in base 10.
num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);
Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.
For example
5 - 7.6 = -2.5999999999999996
#cr05s19xx suggested on a duplicate question:
JavaScript is a bit funny when it comes to numbers and addition.
Giving the following
'20' - '30' = 10; // returns 10 as a number
'20' + '30' = '2030'; // Returns them as a string
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
Use the parseFloat method to parse the strings into floating point numbers:
parseFloat(num1) + parseFloat(num2)
I use this in my project.I use + sign to treat string as a number (in with_interesst variable)
<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest = PHP"+with_interesst;
}
</script>
<div name="printchatbox" id="printchatbox">
<form id="Calculate" class="form-horizontal">
<h2>You Can Use This Calculator Before Submit </h2>
<p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
<option value="40">40 Days</option>
<option value="50">50 Days</option>
<option value="60">60 Days</option>
<option value="70">70 Days</option>
<option value="80">80 Days</option>
<option value="90">90 Days</option>
<option value="100">100 Days</option>
<option value="120">120 Days</option>
</select>
</p>
<h2 id="payment"></h2>
<h2 id ="with_interesst"></h2>
</form>
</div>
Hope it helps
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
You may use like this:
var num1 = '20',
num2 = '30.5';
alert((num1*1) + (num2*1)); //result 50.5
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
How can I force these strings to be treated as numbers?
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
(+varname)
So, in your case it's:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
convert the strings to floats with parseFloat(string) or to integers with parseInt(string)
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
You can use this to add numbers:
var x = +num1 + +num2;
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
http://www.crockford.com/
http://javascript.crockford.com/
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
I've always just subtracted zero.
num1-0 + num2-0;
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
Here, you have two options to do this :-
1.You can use the unary plus to convert string number into integer.
2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
Using parsing approach-
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
You can use parseInt to parse a string to a number. To be on the safe side of things, always pass 10 as the second argument to parse in base 10.
num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);
Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.
For example
5 - 7.6 = -2.5999999999999996
#cr05s19xx suggested on a duplicate question:
JavaScript is a bit funny when it comes to numbers and addition.
Giving the following
'20' - '30' = 10; // returns 10 as a number
'20' + '30' = '2030'; // Returns them as a string
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
Use the parseFloat method to parse the strings into floating point numbers:
parseFloat(num1) + parseFloat(num2)
I use this in my project.I use + sign to treat string as a number (in with_interesst variable)
<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest = PHP"+with_interesst;
}
</script>
<div name="printchatbox" id="printchatbox">
<form id="Calculate" class="form-horizontal">
<h2>You Can Use This Calculator Before Submit </h2>
<p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
<option value="40">40 Days</option>
<option value="50">50 Days</option>
<option value="60">60 Days</option>
<option value="70">70 Days</option>
<option value="80">80 Days</option>
<option value="90">90 Days</option>
<option value="100">100 Days</option>
<option value="120">120 Days</option>
</select>
</p>
<h2 id="payment"></h2>
<h2 id ="with_interesst"></h2>
</form>
</div>
Hope it helps
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
You may use like this:
var num1 = '20',
num2 = '30.5';
alert((num1*1) + (num2*1)); //result 50.5
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
How can I force these strings to be treated as numbers?
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
(+varname)
So, in your case it's:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
convert the strings to floats with parseFloat(string) or to integers with parseInt(string)
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
You can use this to add numbers:
var x = +num1 + +num2;
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
http://www.crockford.com/
http://javascript.crockford.com/
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
I've always just subtracted zero.
num1-0 + num2-0;
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
Here, you have two options to do this :-
1.You can use the unary plus to convert string number into integer.
2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
Using parsing approach-
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
You can use parseInt to parse a string to a number. To be on the safe side of things, always pass 10 as the second argument to parse in base 10.
num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);
Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.
For example
5 - 7.6 = -2.5999999999999996
#cr05s19xx suggested on a duplicate question:
JavaScript is a bit funny when it comes to numbers and addition.
Giving the following
'20' - '30' = 10; // returns 10 as a number
'20' + '30' = '2030'; // Returns them as a string
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
Use the parseFloat method to parse the strings into floating point numbers:
parseFloat(num1) + parseFloat(num2)
I use this in my project.I use + sign to treat string as a number (in with_interesst variable)
<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest = PHP"+with_interesst;
}
</script>
<div name="printchatbox" id="printchatbox">
<form id="Calculate" class="form-horizontal">
<h2>You Can Use This Calculator Before Submit </h2>
<p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
<option value="40">40 Days</option>
<option value="50">50 Days</option>
<option value="60">60 Days</option>
<option value="70">70 Days</option>
<option value="80">80 Days</option>
<option value="90">90 Days</option>
<option value="100">100 Days</option>
<option value="120">120 Days</option>
</select>
</p>
<h2 id="payment"></h2>
<h2 id ="with_interesst"></h2>
</form>
</div>
Hope it helps
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
You may use like this:
var num1 = '20',
num2 = '30.5';
alert((num1*1) + (num2*1)); //result 50.5
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html
I think the JS thought that var num was a String, but I want var num as a number! The problem says 'num' is not defined.
var num = document.getElementById('number').value;
var i = Math.floor(Math.random(0,num));
var c = document.getElementById('chance').value;
function clicked(){
var j = document.getElementById('game').value;
if (i > j){
document.getElementById('demo').innerHTML = "Bigger!";
c -= 1;
document.getElementById('re').innerHTML = "You have " + c + " more chances!";
} else if(num < j){
document.getElementById('demo').innerHTML = "The value is bigger than " + num + "!";
document.getElementById('re').innerHTML = " "
} else if (i < j){
document.getElementById('demo').innerHTML = "Smaller!";
c -= 1;
document.getElementById('re').innerHTML = "You have " + c + " more chances";
} else if (i == j){
document.getElementById('demo').innerHTML = "Correct!";
c = 14;
document.getElementById('re').innerHTML = " ";
i = Math.floor(Math.random()*num);
}
if (c == 0){
document.getElementById('demo').innerHTML = "Try again! The secret number was " + num;
c = 14;
document.getElementById('re').innerHTML = " ";
i = Math.floor(Math.random()*101);
}
}
<p>
You should guess a number between 0 ~ <input type="number" id="number"> under this text. You have total <input type="number" id="chance"> chances. Good luck!<br><br>
<input type="number" id="game"> <input type="submit" onclick="clicked()" value="GUESSED">
<p id="demo"></p>
<p id="re"></p>
</p>
I want an ID 'number' be var num, the random number between 0 and num:
which will be the var I, and an ID 'chance' be var c, the number of chances be the c. I hope you know what I mean, because I described precisely as I can. By the way, I am coding a number guessing game HTML and I am a coding nooooob. If you are nice, please help me out. Thank You.
See doc : https://gomakethings.com/converting-strings-to-numbers-with-vanilla-javascript/
var num1 = parseInt(num, 10);
The parseInt() method converts a string into an integer (a whole number).
It accepts two arguments. The first argument is the string to convert. The second argument is called the radix. This is the base number used in mathematical systems. For our use, it should always be 10.
The Number() method converts a string to a number.
Sometimes it’s an integer. Other times it’s a point number. And if you pass in a string with random text in it, you’ll get NaN, an acronym for “Not a Number.”
As a result of this inconsistency, it’s a less safe choice than parseInt() and parseFloat(). If you know the format of the number you’d like, use those instead. If you want the string to fail with NaN if it has other characters in it, Number() may actually be a better choice.
var num = document.getElementById('number').value always returns a string value. You can cast the value using https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
num = Number(num);
I have a working decimal to binary converter, but I want it to ALWAYS show 8 digits,
so if I put in 3 it will say '00000011' and not '11'
Anyone a clue how this can be done?
my code:
<script type="text/javascript">
function ConvertToBinary(dec) {
var bits = [];
var dividend = dec;
var remainder = 0;
while (dividend >= 2) {
remainder = dividend % 2;
bits.push(remainder);
dividend = (dividend - remainder) / 2;
}
bits.push(dividend);
bits.reverse();
return bits.join("");
}
<input type="text" id="txtDec" maxlength="3"/>
<input type="button" value="Convert" onclick="document.getElementById('spBin').innerHTML=ConvertToBinary(document.getElementById('txtDec').value);" />
<span id="spBin"></span>
JavaScript already makes the conversion for you, from a number, using toString method, because you can specify the radix (see the link above):
var n = 13;
console.log(n.toString(2)) // "1101"
If you want add lead zero, in case less then 8, you could have:
var bits = n.toString(2);
console.log("00000000".substr(bits.length) + bits);
With just one method call.
Edit: this answer was written in 2013, nowadays the method padStart can be used instead for the padding:
console.log(n.toString(2).padStart(8, "0"));
How about this:
return String('000000000' + bits.join("")).slice(-8);
Demo (change "dividend" to try with different numbers)
Basically adds 8 zeros to the left and then removes anything more than 8 characters long from the left.
How about before bits.reverse(); You do a while loop like this:
while(bits.length < 8){
bits.push(0);
}
Here's an example solution that will left-pad a number with zeros
#param "num" the number to be left-padded with zeros
#param "width" the number of characters required as a result
#return String the left-padded number
function zeroFill(num, width) {
str = String((new Array(width+1)).join('0') + num).slice(-width)
return str
}
There are other solutions which use a loop to create the zeros.