The numeric value for entering the number by the user in the text field

I need to add two numbers entered by the user. To do this, I create two input fields, extract the values ​​from them using .val () in two separate variables, and then add them. The problem is that strings are added, not numbers. E.g. 2 + 3 becomes 23, not 5. please suggest what to do, except for using type = number in the input field.

+6
source share
4 answers

You can use parseInt (...)

Example:

var num = parseInt("2", 10) + parseInt("3", 10); // num == 5 
+6
source

Use parseInt to convert a string to a number:

 var a = '2'; var b = '3'; var sum = parseInt(a,10) + parseInt(b,10); console.log(sum); /* 5 */ 

Keep in mind that parseInt(str, rad) only works if str actually contains several base rad , so if you want to allow other bases, you will need to manually check them. Also note that you need to use parseFloat if you want more integers.

+4
source

Either use parseInt (http://www.w3schools.com/jsref/jsref_parseint.asp) or parseFloat (http://www.w3schools.com/jsref/jsref_parsefloat.asp) to convert to a numeric value before adding.

PS: This is a simple answer. You might want to do some checks / deletions / trimming, etc.

0
source

Number () is the function you want "123a" returns NAN

parseInt () truncates the final letters "123a" returns 123

 <input type="text" id="txtFld" onblur="if(!Number(this.value)){alert('not a number');}" /> 
0
source

Source: https://habr.com/ru/post/908445/


All Articles