Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

String to Number in JavaScript

There are several ways you can convert JavaScript String to Number. The best way is to make use of the unary plus + operator or the Number global function. You can also make use of the parseint or parsefloat functions. The following examples show how to make use of these functions.

Unary plus (+)

The Unary plus (+) operator converts all string representations of numbers, Boolean values(true and false), and null to numbers. If the operand cannot be converted into a number, the unary plus operator will return NaN

The following are some of the examples

                              
console.log(+"100")                 //100
console.log(+"100.5175")            //100.5175
console.log(+"10AA0.5175")          //NaN
console.log(+"")                    //0
console.log(+" ")                   //0
console.log(+null)                  //0
console.log(+undefined)             //Nan 
console.log(+Infinity)              //Infinity
console.log(+true)                  //1
console.log(+false)                 //0
console.log(+"0x22")                //34
console.log(+"0022")                //22
console.log(+"0o51")                //41
console.log(+"3.125e7")             //31250000
console.log(+"35 35")               //NaN
console.log(+"AB 35")               //NaN
 
                            
                            
                        
  1. Tries to convert any string to a number
  2. It converts empty string / Null to 0
  3. True is 1 and False is 0
  4. Converts Octal/Hex numbers to decimal.
  5. Works correctly on scientific notation numbers.
  6. In case it fails to convert, then returnsNaN

Parseint

The parseint function parses an string and returns an integer. The syntax of the parseint is as follows. If you do not provide the radix then it assumes the Hexadecimal number.

parseInt(string, radix)

                              
console.log(parseInt("100"))                   //100
console.log(parseInt("100.5175"))              //100 
console.log(parseInt("10AA0.5175"))            //10
console.log(parseInt(""))                      //NaN
console.log(parseInt(null))                    //NaN 
console.log(parseInt(Infinity))                //NaN
console.log(parseInt(true))                    //NaN    
console.log(parseInt(false))                   //NaN
console.log(parseInt("0x22"))                  //34 
console.log(parseInt("0022"))                  //22
console.log(parseInt("0o51"))                  //0
console.log(parseInt("3.125e7"))               //3
console.log(parseInt("35 35"))                 //35
console.log(parseInt("AB 35"))                 //NaN
 
                            
                            
                        
  1. Tries to convert any string to a integer and not to floating number
  2. Converts empty strings, null, infinity, True & false to a NaN
  3. If the string begins with 0x then it treats it a Hexadecimal number.
  4. It does not recognize the octal number that begins with 0o
  5. The older browsers will treat the number starting with 0as Octal.
  6. Ignores the Leading & trailing spaces
  7. If only the initial part of the string is a number, then it converts into number and ignores the rest.

You can make use of the radix. The radix can be from 2 to 36. Use span style="color: grey; background-color: powder;"2 for binary,8 for octal, 10 for decimal & 16 for HexaDecimal number.

                              
console.log(parseInt("51"));                //51
console.log(parseInt("51",8));              //41
console.log(parseInt("51",16));             //81
 
console.log(parseInt("051"));               //51
console.log(parseInt("051",8));             //41 
console.log(parseInt("051",16));            //81
 
console.log(parseInt("0x51"));               //81
console.log(parseInt("0x51",8));             //0
console.log(parseInt("0x51",16));            //81
 
console.log(parseInt("0o51"));               //0
console.log(parseInt("0o51",8));             //0 
console.log(parseInt("0o51",16));            //0 
 
                            
                            
                        

Parsefloat

ParseFloat is another way to convert string to a number.

                              
console.log(parseFloat("100"))                  //100
console.log(parseFloat("100.5175"))             //100.5175
console.log(parseFloat("10AA0.5175"))           //10
console.log(parseFloat(""))                     //NaN
console.log(parseFloat(null))                   //NaN 
console.log(parseFloat(Infinity))               //Infinity
console.log(parseFloat(true))                   //NaN    
console.log(parseFloat(false))                  //NaN
console.log(parseFloat("0x22"))                 //0 
console.log(parseFloat("0022"))                 //22
console.log(parseFloat("0o51"))                 //0
console.log(parseFloat("3.125e7"))              //31250000
console.log(parseFloat("35 35"))                //35
console.log(parseFloat("AB 35"))                //NaN 
 
                            
                            
                        
  1. Tries to convert any string to a integer and not to floating number
  2. Converts empty strings, null, infinity, True & false to a NaN
  3. Returns infinity as it is.
  4. It the string begins with 0x or 0o it returns zero. Does not recognize Hexa decimal or octal numbers
  5. The older browsers will treat the number starting with 0as Octal.
  6. Ignores the Leading & trailing spaces
  7. If only the initial part of the string is a number, then it converts into number and ignores the rest.

Number global function

You can also use the Number global function. It is very similar to unary plus (+)

                              
console.log(Number("100"))                  //100
console.log(Number("100.5175"))             //100.5175
console.log(Number("10AA0.5175"))           //NaN 
console.log(Number(""))                     //0
console.log(Number(" "))                    //0
console.log(Number(null))                   //0
console.log(Number(undefined))              //Nan    
console.log(Number(Infinity))               //Infinity
console.log(Number(true))                   //1
console.log(Number(false))                  //0 
console.log(Number("0x22"))                 //34 
console.log(Number("0022"))                 //22
console.log(Number("0o51"))                 //41  
console.log(Number("3.125e7"))              //31250000
console.log(Number("35 35"))                //NaN
console.log(Number("AB 35"))                //NaN
 
                            
                            
                        
  1. Tries to convert any string to a integer and not to floating number
  2. It converts empty string / Null to 0
  3. True is 1 and False is 0
  4. Converts Octal/Hex numbers to decimal./li>
  5. Works correctly on scientific notation numbers.
  6. In case it fails to convert, then returns NaN

Check for NaN

The string to number operation may result in a NaN. The NaN stands for not a number. It is the result of numerical operations, where the result is not a number. Hence always check if the value is NaN using the isNaN method after the conversion.

                              
convertToNumber("AB 35")
convertToNumber("35")
 
function convertToNumber(numVal) {
  
  if (isNaN(+numVal)) {
    console.log("Number is NaN")
    
  } else  {
    console.log(+numVal)
  }
}
 
//Output
Number is NaN
35