How to use built-in JavaScript functions like parseInt and parseFloat?

To use built-in JavaScript functions like parseInt and parseFloat, you can follow these steps:

  1. parseInt function: It converts a string to an integer.

    Example:

    let numberString = '123'; let number = parseInt(numberString); console.log(number); // Output: 123
  2. parseFloat function: It converts a string to a floating-point number.

    Example:

    let decimalString = '3.14'; let decimal = parseFloat(decimalString); console.log(decimal); // Output: 3.14

Both the parseInt and parseFloat functions take a string as their argument and return the parsed number. If the provided string cannot be converted to a valid number, these functions will return NaN (Not-a-Number). Therefore, it is a good practice to check for NaN after parsing.

It is also worth mentioning that parseInt and parseFloat can take an optional second argument called the radix. The radix specifies the base of the numeral system used in the string. If not provided, it defaults to 10. For instance, to parse a hexadecimal number, you would pass 16 as the radix.

Example using radix:

let hexString = 'FF'; let decimalFromHex = parseInt(hexString, 16); console.log(decimalFromHex); // Output: 255

In summary, you can use parseInt and parseFloat functions by passing a string as an argument to get the desired numeric value.