Middle
What string conversion methods do you know?
sobes.tech AI
Answer from AI
There are several ways to convert a string to a number in JavaScript:
- Number() — converts a string to a number, returns NaN if conversion is impossible.
Number('123'); // 123
Number('12.34'); // 12.34
Number('abc'); // NaN
- parseInt() — parses an integer from the beginning of the string, ignoring subsequent characters.
parseInt('123abc'); // 123
parseInt('12.34'); // 12
- parseFloat() — parses a floating-point number from the beginning of the string.
parseFloat('12.34abc'); // 12.34
- Unary plus (+) — a quick way to convert a string to a number.
+'123'; // 123
+'12.34'; // 12.34
+'abc'; // NaN
- Math.floor(), Math.ceil(), Math.round() — can be used after conversion for rounding.
The choice of method depends on the task: use parseInt for integers, and parseFloat or Number for floating-point numbers.