How can you convert the string '3.14' to a number in JavaScript?
Answers
Number('3.14')
parseNum('3.14')
int('3.14')
parseFloat('3.14')
# Converting Strings to Numbers in JavaScript
In JavaScript, there are several ways to convert a string to a number, regardless of whether the string contains an integer or a floating point. In the quiz, we learned that you can convert the string '3.14' to a number using, `Number('3.14')` and `parseFloat('3.14')`.
## The Number() Function
The `Number()` function works by trying to convert its argument into a number. Look at the following example:
```javascript
let str = '3.14';
let num = Number(str);
console.log(num); // Output: 3.14
```
In the code above, we converted a string '3.14' to a number 3.14 using `Number()`. If the string cannot be converted into a number, it will return `NaN`.
## The parseFloat() Function
Another function that can convert a string into a number is `parseFloat()`. This function converts its string argument into a floating-point number.
```javascript
let str = '3.14';
let num = parseFloat(str);
console.log(num); // Output: 3.14
```
In the above example, `parseFloat('3.14')` returns the same result as `Number('3.14')`, a number 3.14. If the string argument cannot be converted to a floating-point number, this function will return `NaN`.
An important point to remember with `parseFloat` is that it stops parsing a string when it encounters a non-numeric character (except dot '.' for decimal). For example:
```javascript
let str = '3.14abc';
let num = parseFloat(str);
console.log(num); // Output: 3.14
```
## Best Practices
In many cases, `Number()` and `parseFloat()` are interchangeable when you're dealing with numeric strings. However, remember that `parseFloat()` is more forgiving and can parse numbers embedded in non-numeric strings.
Do note that in situations where you're working with integers, the `parseInt()` function is more suitable, as it parses a string argument and returns an integer, and stops parsing when it encounters a non-numeric character, similar to `parseFloat()`.
Use these functions wisely based on the type of strings you're dealing with. Remember, well-crafted code is all about understanding and using the features of the language to their fullest, and using the correct function at the correct place!