How to use the parseInt and parseFloat functions in JavaScript to convert strings to numbers

The parseInt() and parseFloat() functions in JavaScript are used to convert strings to integers and floating-point numbers, respectively. These functions can be helpful when you need to perform arithmetic operations on data that is stored as a string.

Here's how to use the parseInt() function:

var num = parseInt('10');
console.log(num); // Outputs 10

The parseInt() function takes a string as an argument and returns an integer. If the string cannot be converted to an integer, the function returns NaN (Not a Number).

Here's how to use the parseFloat() function:

var num = parseFloat('3.14');
console.log(num); // Outputs 3.14

The parseFloat() function takes a string as an argument and returns a floating-point number. If the string cannot be converted to a floating-point number, the function returns NaN.

Both the parseInt() and parseFloat() functions have an optional second argument called the "radix," which specifies the base of the number being parsed. For example:

var num = parseInt('11', 2); // Parses the binary string '11' as a base-2 (binary) number
console.log(num); // Outputs 3

var num = parseInt('FF', 16); // Parses the hexadecimal string 'FF' as a base-16 (hexadecimal) number console.log(num); // Outputs 255

By using the parseInt() and parseFloat() functions, you can easily convert strings to numbers in JavaScript. This can be helpful when you need to perform arithmetic operations on data that is stored as a string, or when you need to convert data from a string format to a numerical format.

Additional resources
  • Frontend web development courses

    Beginner-friendly courses focusing on HTML, CSS, and JavaScript.

    View Courses
  • Frontend web development projects

    Beginner-friendly projects focusing on HTML, CSS, and JavaScript.

    View Projects
  • Free website templates

    Collection of free, high-quality website templates for your next project.

    View Templates