As below, using the native function parseInt
of Javascript
, you can convert a String
to a Int
:
var number1 = parseInt('10'),
number2 = parseInt('100'),
result = number1 + number2;//Resultado: 110
Optionally you can also pass a second parameter in the parseInt
function, which indicates which numeric system you want to be converted, for example by converting to the decimal base:
Converting to decimal base:
var number1 = parseInt('21', 10),
number2 = parseInt('30', 10),
result = number1 + number2;//Resultado: 51
Converting to binary base:
var number1 = parseInt('011', 2),//3 em decimal
number2 = parseInt('010', 2),//2 em decimal
result = number1 + number2;//5 em decimal
Another option for conversion would be to use the Number class, as follows:
var number1 = Number("10"),
number2 = Number("10"),
result = number1 + number2;//20
However, using it when there is any text character, the conversion returns NaN - Not A Number (not a number), for example:
var number1 = Number("10a"),//NaN
number2 = Number("10"),//10
result = number1 + number2;//NaN
While using parseInt, it would treat the String and convert "10a" to "10", as in the example:
var number1 = parseInt("10a"),//10
number2 = parseInt("10"),//10
result = number1 + number2;//20
In your case it could look like this:
var inputvalue1 = parseInt(document.getElementById('myinput1').value);
var inputvalue2 = parseInt(document.getElementById('myinput2').value);
Solution that could be applied to your code:
function somar(a, b) {
var inputvalue1 = parseInt(a.value),
inputvalue2 = parseInt(b.value),
result = inputvalue1 + inputvalue2;
document.getElementById('demo').innerHTML = result;
}
<input type="number" id="myinput1">
<input type="number" id="myinput2">
<button type="button" onclick="somar(myinput1, myinput2)">Somar</button>
<p id="demo">Soma entre os valores colocados aqui</p>
Another solution without the use of paramaters in the add function:
function somar() {
var inputvalue1 = parseInt(document.getElementById('myinput1').value),
inputvalue2 = parseInt(document.getElementById('myinput2').value),
result = inputvalue1 + inputvalue2;
document.getElementById('demo').innerHTML = result;
}
<input type="number" id="myinput1">
<input type="number" id="myinput2">
<button type="button" onclick="somar()">Somar</button>
<p id="demo">Soma entre os valores colocados aqui</p>
Remembering that, for greater security, it would be better to treat the input data from input's
, as this would avoid performing the calculation with entries other than numbers. For example:
var number = 'text';
if (!isNaN(number)) {
alert('É número!');
} else {
alert('Não é número!');
}