Cubepost Technology Developer World Politics News Learn Gadgets Arts Play Cubepost Technology Developer World Politics News Learn Gadgets Arts Play Cubepost Technology Developer World Politics News Learn Gadgets Arts Play Cubepost Technology Developer World Politics News Learn Gadgets Arts Play

Node JS Convert String to Integer, ParseInt() Function - Javascript

Cubepost, Jul 31, 2020

Javascript Based - Node JS, Jquery uses ParseInt() function which takes a string and optional radix parameter to convert to integer

Usage of parseInt() in Javascript

The parseInt() function parses a string and returns an integer in javacript.
 javascript node js jquery typescript 

parseInt(Value string, radix integer);
Paramters
      Value: [Required, String] String value passed to convert to integer
      radix:  [Optional, Integer] Value 0 - 32, The radix or the base value to be considered 


Simple Usage:

x,text/javascript,index.js
const a = '5';
const b = parseInt(a);
console.log(b); // Output => 5  


Advanced Usage:
Note: parseInt() will output some weird results if there are leading 0's in the string. In older versions , parseInt("03010123"); //output: 790611 
The problem is because older node js or browsers consider the radix defaults to 8 (octal), Currently, now all are radix 10 (decimal) version.

1. Convert numbers to base 8 (octal)

x,text/javascript,index.js
const a = '050';
const b = parseInt(a, 8);  // Base 8
console.log(b); // Output => 40  


2. starting with a character this function gives NaN, Not a number

x,text/javascript,index.js
const a = 'a5';
const b = parseInt(a);
console.log(b); // Output => NaN


3. first occurring of space is considered the end of the integer

x,text/javascript,index.js
const a = '25 60 30';
const b = parseInt(a);
console.log(b); // Output => 25  


4. Leading 0s in Base 10 decimal or default is removed

x,text/javascript,index.js
const a = '00568';
const b = parseInt(a);
console.log(b); // Output => 568


5. Base 8 octal version of string value 10

x,text/javascript,index.js
const a = '10';
const b = parseInt(a, 8);
console.log(b); // Output => 8


Number System: 

Most commonly used number system are listed

Javascript Learns
5750704903815168-javascript-nodejs-cubepost.png

W3 Schools

Cubepost, Jul 31, 2020
cubepost-logo

Allow Updates from cubepost.red

Not Allow

Allow