Sobes.tech
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:

  1. Number() — converts a string to a number, returns NaN if conversion is impossible.
Number('123'); // 123
Number('12.34'); // 12.34
Number('abc'); // NaN
  1. parseInt() — parses an integer from the beginning of the string, ignoring subsequent characters.
parseInt('123abc'); // 123
parseInt('12.34'); // 12
  1. parseFloat() — parses a floating-point number from the beginning of the string.
parseFloat('12.34abc'); // 12.34
  1. Unary plus (+) — a quick way to convert a string to a number.
+'123'; // 123
+'12.34'; // 12.34
+'abc'; // NaN
  1. 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.

What string conversion methods do you know? — Frontend - sobes.tech