There are multiple ways to convert a given string to a number - so, which one to use and where?
You would have also seen the more generic post on how to cast value from one type to another. But it may not be so apparent on which option to pick when you need to get numbers from a given string.
The first approach is my preferred one.
The values returned by
Number evaluate to
false as expected. You could easily check for valid numbers and abandon operation if the string is
not a number.
The second approach is very similar to the above, except it provides an integer. However, you need to be careful about strings that start with numbers -
parseInt extracts those numbers to provide a valid number even though the complete string is not a number.
The third approach is to use
parseFloat, which behaves exactly like
parseInt except that it returns floating point numbers.
I prefer using
Number almost all the time since I typically do not want half-strings to be evaluated as numbers.