This post will discuss how to convert a string to a float or an integer in JavaScript.

We might need to convert a string to a numerical value that can be used for calculations or comparisons. There are several ways to convert a string to a float or an integer in JavaScript. Here are some of the most common functions:

1. Using parseFloat() function

One way is to use the parseFloat() function, which parses a string argument and returns a floating point number. We can use the parseFloat() function to parse a string to a float by passing the string as an argument. For example, if we have a string "3.14", we can convert it to a float using parseFloat() like this:

Download  Run Code

 
This function will ignore any leading or trailing whitespace in the string, and will stop parsing when it encounters an invalid character. If the string is not a valid number, the function returns NaN.

2. Using parseInt() function

Another way is to use the parseInt() function, which parses a string argument and returns an integer number. We can use this function to parse a string to an integer by passing the string as argument. The function returns an integer that represents the value of the string in base 10. For example, the following code convert the string "100" to an integer:

Download  Run Code

 
If the string is not a valid number, this function returns NaN. It will also ignore any leading or trailing whitespace in the string, and will stop parsing when it encounters an invalid character. Additionally, we can pass a second argument to specify the radix (base) of the number system we want to use. The radix is an integer between 2 and 36 that represents the base of the number system. For example, 10 means decimal, 16 means hexadecimal, and 2 means binary. The following code illustrates this:

Download  Run Code

3. Using Number() function

A third way is to use the Number() function, which converts a JavaScript value or object to a number. We can use the Number() function to parse a string to a float or an integer by passing the string as an argument. The Number() function returns a number that represents the value of the string. For example, if we have a string "2.5", we can convert it to a number using Number() like this:

Download  Run Code

 
This function will also return NaN if the value cannot be converted to a number. Unlike parseFloat() and parseInt(), this function will not ignore any trailing characters in the string. Here’s an example:

Download  Run Code

4. Using unary plus operator

A fourth way is to use the unary plus operator, which converts its operand to a number. This operator will also return NaN if the operand cannot be converted to a number. It has the same behavior as the Number() function in terms of handling trailing characters. For example, if we have a string "7.8", we can convert it to a number using unary plus like this:

Download  Run Code

That’s all about converting a string to a float or an integer in JavaScript.