Sobes.tech
Junior

How does string to number conversion happen in JavaScript?

sobes.tech AI

Answer from AI

In JavaScript, converting a string to a number can be done in several ways:

  • Implicit type coercion:

    • Mathematical operators: For example, unary plus + or subtraction -.
    // Implicit coercion using unary plus
    let str = "123";
    let num = +str; // num = 123 (number)
    
    • Arithmetic operations: When using arithmetic operators, JavaScript attempts to convert operands to numbers.
    // Implicit coercion with subtraction
    let str1 = "10";
    let str2 = "5";
    let result = str1 - str2; // result = 5 (number)
    
  • Explicit type conversion:

    • parseInt(string, radix): Converts a string to an integer. The second argument radix (numeral system base) is recommended to specify to avoid unexpected behavior.
    // Explicit conversion with parseInt
    let strInt = "42px";
    let numInt = parseInt(strInt, 10); // numInt = 42 (integer)
    
    let strBinary = "101";
    let numBinary = parseInt(strBinary, 2); // numBinary = 5 (integer)
    
    • parseFloat(string): Converts a string to a floating-point number. Parses the string until the first non-numeric character or dot.
    // Explicit conversion with parseFloat
    let strFloat = "3.14abc";
    let numFloat = parseFloat(strFloat); // numFloat = 3.14 (floating-point number)
    
    • Number(value): Converts any value to a number. A more strict approach compared to parseInt and parseFloat. If the string cannot be fully converted to a number, it returns NaN.
    // Explicit conversion with Number
    let strNum = "123.45";
    let numFromNumber = Number(strNum); // numFromNumber = 123.45 (number)
    
    let strInvalid = "hello";
    let numInvalid = Number(strInvalid); // numInvalid = NaN
    

Differences and features:

Method Description Returns on invalid string Parses from start to first non-number
+string Implicit coercion with unary plus. NaN No (entire string)
string - 0 Implicit coercion with subtraction. NaN No (entire string)
parseInt() Parses an integer. NaN Yes
parseFloat() Parses a floating-point number. NaN Yes
Number() Explicit conversion. More strict. NaN No (entire string)

The choice of method depends on the specific task and the expected format of the input string. Number() is preferred for converting strings representing whole or fractional numbers without extra characters. parseInt() and parseFloat() are useful for extracting numeric values from strings containing additional characters (e.g., units). Implicit coercion should be used cautiously, understanding its behavior.