How to convert a String to Int in Javascript?

Asked

Viewed 48,238 times

9

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 am trying to add two numbers I receive from the inputs, unfortunately I receive the values as strings causing the problem (1+1=11). I’m starting to learn JS so I wanted to know how to convert incoming strings to int. Use firefox 47.0 comment if you need any information.

4 answers

13


As follows below using the native function parseInt of Javascript, you can convert a String for 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 numeric system you want to be converted, for example by converting to decimal basis:

Converting to decimal basis:

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 using the Number class, as follows:

var number1 = Number("10"),
    number2 = Number("10"),
    result = number1 + number2;//20

However, using it when there is a 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 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 might look like this:

var inputvalue1 = parseInt(document.getElementById('myinput1').value);
var inputvalue2 = parseInt(document.getElementById('myinput2').value);

Solution that could be applied in 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 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>

Recalling that, for greater security, it would be better to make a treatment in the input data from input's, thus avoiding 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!');
}
  • 1

    Example of error handling failure for input '0'. parseInt returns NaN in case of conversion failure, then prefer to use the function isNaN in your if test, which was made to test this.

  • Thanks helped a lot! But it is necessary to refer to the value of the var inputvalue1= parseInt(a.value),... even though I referred to him before?var inputvalue1 = document.getElementById('myinput1').value;

  • Give to do both ways using with the parameters a and b the way I did, or without parameters, using Document.getElementById('myinput1'). value within the function to pick up input values.

6

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 may contain decimal places:

var x = Math.floor("1000.01");

Example for testing:

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>

0

You can also convert a String to Integer Number like this:

~~"123.213" // => 123

-2

// 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.*/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.