How to many ways to convert string to number in Javascript

Dung Do Tien Feb 12 2020 199

In my sample app, I need to addition two number, one is string type and other number type.

<script>
  var a = "5";
  var b = 10;
  alert(a + b)
</script>

I get result 510. How can I make it result to 15? How many way to do?

Have 1 answer(s) found.
  • Hello,

    In Javascript have some rule for addition(+) operator :

    - string + string = string

    - string + number = string

    - string + bool = string

    - string + datetime = string ....

    And "5" + 10 = "510" is alright.

     

    How to convert string to number? have some way bellow :

    1. Use parseInt() Or parseFloat()

    var a = "5";
    a = parseInt(a) // return 5 and convert to integer number
    
    var b = "5.5";
    b = parseFloat(b) // return 5.5 and convert to float data type 
    

    See demo

     

    2. Use Number() method

    var age = Number("3") + 5;
    alert(age); // age = 8 
    

    See demo

     

    3. Using operator  +   before value string.

    var age =+"90"; 
    alert(typeof age); // alert "number"
    var age1 =+"10";
    alert(age + age1); // alert 100
    

    See demo

     

    4. Using Multiply by 1(* 1)

    var age ="90" * 1; 
    alert(typeof age); // alert "number"
    var age1 ="10" *1;
    alert(age + age1); // alert 100

    See demo

    So we have 4 ways to convert string to number in javascript. About performance, you can choose way 4 for the best performance.

    Manish Kumar Apr 03 2020
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips