How to convert a String to Int in Javascript?
HTML5:
<!DOCTYPE html>
<html>
<head>
<title>JSTest</title>
<meta charset="UTF-8">
<script src="JSource.js"></script>
</head>
<body>
<input type="number" id="myinput1">
<input type="number" id="myinput2">
<button type="button" onclick="somar(inputvalue1,inputvalue2)">Somar</button>
<p id="demo">Soma entre os valores colocados aqui</p>
<script>
var inputvalue1 = document.getElementById('myinput1').value;
var inputvalue2 = document.getElementById('myinput2').value;
</script>
</body>
</html>
Javascript:
function somar(a,b) {
var result = a+b;
document.getElementById("demo").innerHTML = result;
alert(typeof(a)+" "+typeof(b));
}
I'm trying to sum two numbers I get from the inputs, unfortunately I get the values as strings causing the problem (1+1=11).I'm starting to learn JS so I wanted to know how to convert the received strings to int. Use firefox 47.0 comment if you need any information.
4 answers
As follows 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 function parseInt
, which indicates which numerical 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 it would be using the number class, as follows:
var number1 = Number("10"),
number2 = Number("10"),
result = number1 + number2;//20
However, using it when there is some text character, the conversion returns NaN - 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 using parameters in the sum 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 do a treatment in the input data coming from the input's
, as this would avoid the execution of the calculation with entries other than numbers. For example:
var number = 'text';
if (!isNaN(number)) {
alert('É número!');
} else {
alert('Não é número!');
}
You can perform the conversion as follows:
If the value is an integer:
var x = parseInt("1000", 10);
Or
Number("1000");
If the value contains or can contain decimal places:
var x = Math.floor("1000.01");
Example for tests:
function somar() {
var inputvalue1 = Number(document.getElementById('myinput1').value);
var inputvalue2 = Number(document.getElementById('myinput2').value);
alert(inputvalue1 + inputvalue2);
}
<input type="number" id="myinput1">
<input type="number" id="myinput2">
<button type="button" onclick="somar()">Somar</button>
You can also convert a String to integer number like this:
~~"123.213" // => 123
// Temos aqui um exemplo onde:
let result = (7 + 13) / (9 + 7);
let result2 = 100 / (2 * 6);
let finalResult = (result * result2);
typeof finalResult; // retorna 'string'
// então podemos:
if (typeof finalResult === "string"){
finalNumber = Number(finalResult);
} else
finalNumber = finalResult;
console.log(finalNumber);
/*Neste caso, Atribuímos a variável alvo o valor "Number(finalResult)", isto é o valor finalResult vai ser convertido para Number.*/