String to Number Conversion in JavaScript

The parseInt() and parseFloat() are commonly used functions in JavaScript to parse the string into number according to your needs. The parseFloat() function parses a string and returns an a floating point number.
If the string is the alphanumeric then it will parse the number found in the beginning of the string otherwise If the first character cannot be converted to a number, parseFloat returns NaN.

The following code snippet demonstrates the use of the parse parseFloat() function and the results.

document.write(parseFloat('1.32kg')+ "</br>");  // 1.32
document.write(parseFloat('1.55') + "</br>");   // 1.55
document.write(parseFloat('077.3')+ "</br>");   // 77.3
document.write(parseFloat('0x55.3')+ "</br>");  // 0
document.write(parseFloat('.5') + "</br>" );    // 0.5
document.write(parseFloat('0.1e5')+ "</br>");   // 10000
document.write(parseFloat('hello')+ "</br>");   // NaN
document.write(parseFloat(num)+ "</br>");       // NaN
document.write(parseFloat('89Bond')+ "</br>");   // 89

The parseInt() function parses a string and returns an integer. There is an extra optional parameter in the function that represents the numeral system to be used. You can use the parseInt(string, [numsystem]). If you don’t use this parameter then JavaScript will assume the following:

– If the string begins with “0x”, the numeral system is 16 (hexadecimal)
– If the string begins with “0”, the numeral system is 8 (octal).
– If the string begins with any other value, the numeral system is 10 (decimal)

In the following code, you can understand the use of the parseInt function.

document.write(parseInt('1.32kg')+ "</br>");  // 1
document.write(parseInt('1.55') + "</br>");   // 1
document.write(parseInt('077.3')+ "</br>");   // 77
document.write(parseInt('0x55.3')+ "</br>");  // 85
document.write(parseInt('.5') + "</br>" );    // NaN
document.write(parseInt('0.1e5')+ "</br>");   // 0
document.write(parseInt('hello')+ "</br>");   // NaN
document.write(parseInt(num)+ "</br>");       // NaN
document.write(parseInt('89Bond')+ "</br>");   // 89

You can also use the Number object that is a wrapper object. Number (without using new keyword) can be used to perform a type conversion.

document.write(Number('1.32kg')+ "</br>");  // NaN
document.write(Number('1.55') + "</br>");   // 1.55
document.write(Number('077.3')+ "</br>");   // 77.3
document.write(Number('0x55.3')+ "</br>");  // Nan
document.write(Number('.5') + "</br>" );    // 0.5
document.write(Number('0.1e5')+ "</br>");   // 100000
document.write(Number('hello')+ "</br>");   // NaN
document.write(Number(num)+ "</br>");       // NaN
document.write(Number('89Bond')+ "</br>");   // NaN

There are many ways to convert string to integer value, you can use one of them according to your needs….Thanks