Use parseFloat() function to convert string to number with decimal in JavaScript. This method parses a value as a string and returns the first number.
parseFloat(value)
value: The string value to parse.
Example string to number with decimal in JavaScript
A simple example code converts a string into a point number (a number with decimal points). You can even pass in strings with random text in them.
If the first character cannot be converted, NaN
is returned and Only the first number found is returned.
<!DOCTYPE html>
<html>
<body>
<script>
var text = '3.14someRandomStuff';
var pointNum = parseFloat(text);
console.log(pointNum);
console.log(typeof(pointNum))
</script>
</body>
</html>
Output:
Another example
parseFloat(100);
parseFloat("100");
parseFloat("10.20");
parseFloat("100 45");
parseFloat("Max 10");
For formatting numbers, use toFixed
:
parseFloat("100.10").toFixed(2);
Code
<script>
var text = '10.10';
var pointNum = parseFloat(text).toFixed(2);
console.log(pointNum);
console.log(typeof(pointNum))
</script>
Output: 10.10
Do comment if you have any doubts or suggestions on this JS string to number topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version