Question
What are the methods to convert a string into a number in JavaScript?
const num1 = parseInt('123');
const num2 = parseFloat('123.45');
Answer
In JavaScript, converting a string into a number can be achieved using various built-in methods. This guide explores the primary methods such as `parseInt`, `parseFloat`, and the unary plus operator, covering their usage, syntax, and common pitfalls.
const integer = parseInt('456', 10);
const float = parseFloat('678.90');
const unaryPlus = +'123.45';
console.log(integer, float, unaryPlus);
Causes
- For string to number conversion in JavaScript, it’s essential to identify the format of the string (integer or float).
- Incorrectly specified radix with `parseInt` can lead to unexpected results.
Solutions
- Use `parseInt(string, radix)` to convert strings into integers, where `radix` specifies the base of the numeral system (e.g., 10 for decimal).
- Use `parseFloat(string)` for converting a string to a floating-point number.
- Utilize the unary plus operator (`+string`) for a more concise conversion of both integers and floating-point numbers.
- Always validate the input before performing operations to avoid `NaN` (Not-a-Number) results.
Common Mistakes
Mistake: Using `parseInt` without a radix which can result in unexpected numbers if the string begins with '0'.
Solution: Always specify the radix parameter (e.g., `parseInt('0123', 10)` to ensure it's treated as a decimal).
Mistake: Neglecting to check for `NaN` after conversion which can lead to bugs in calculations.
Solution: Implement checks after conversion like `if (isNaN(number)) { handleError(); }`.
Helpers
- convert string to number
- JavaScript parse string
- number conversion JavaScript
- parseInt example
- parseFloat example