The String() function allows you to get the string representation of the value:
let number1 = "10"; let number2 = 5; let result1 = number1 + String(number2);//105
The parseInt() function is used to convert a string to an integer:
let number3 = "20"; let number4 = 10; let result1 = number4 + parseInt(number3);//30
In this case, the string can have mixed content, for example, “123hello“, that is, in this case there are numbers, but there are and regular characters. The parseInt() function will still try to do the conversion – it’s sequential, starting with first character, reads digits until it encounters the first non-digit character.
If the parseInt() function fails to convert, it returns a NaN (Not a Number) value, which says that the string does not represent a number and cannot be converted.
The isNaN() special function can be used to check if a string represents a number. If the string is not a number, then the function returns true, if this number – then false
To convert strings to fractional numbers, the parseFloat() function is used, which works in a similar way:
let number1 = "10.07"; let number2 = "5.98"; let result = parseFloat(number1) + parseFloat(number2); console.log(result); //16.05