Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
parseFloat() function in JavaScript
The parseFloat() function parses a string and returns a floating-point number. It reads the string from left to right until it encounters a character that cannot be part of a number.
Syntax
parseFloat(string)
Parameters
The function takes only one parameter:
- string - The string to be parsed into a floating-point number
Return Value
Returns a floating-point number parsed from the string. If the first character cannot be converted to a number, it returns NaN.
Example: Basic Usage
<html>
<head>
<title>JavaScript parseFloat Example</title>
</head>
<body>
<script type="text/javascript">
var result1 = parseFloat(Math.PI);
document.write("Result: " + result1);
document.write('<br>');
var result2 = parseFloat("245.12@welcome");
document.write("Result: " + result2);
document.write('<br>');
var result3 = parseFloat("11111100.010");
document.write("Result: " + result3);
</script>
</body>
</html>
Result: 3.141592653589793 Result: 245.12 Result: 11111100.01
Example: Different Input Types
<html>
<head>
<title>parseFloat Examples</title>
</head>
<body>
<script type="text/javascript">
// Valid float strings
document.write("parseFloat('3.14'): " + parseFloat('3.14'));
document.write('<br>');
// String with non-numeric characters
document.write("parseFloat('123.45abc'): " + parseFloat('123.45abc'));
document.write('<br>');
// Leading whitespace is ignored
document.write("parseFloat(' 42.5'): " + parseFloat(' 42.5'));
document.write('<br>');
// Invalid input returns NaN
document.write("parseFloat('hello'): " + parseFloat('hello'));
document.write('<br>');
// Empty string returns NaN
document.write("parseFloat(''): " + parseFloat(''));
</script>
</body>
</html>
parseFloat('3.14'): 3.14
parseFloat('123.45abc'): 123.45
parseFloat(' 42.5'): 42.5
parseFloat('hello'): NaN
parseFloat(''): NaN
Key Points
-
parseFloat()only accepts one parameter, not two likeparseInt() - It stops parsing when it encounters the first invalid character
- Leading whitespace is automatically ignored
- Returns
NaNif no valid number can be parsed - More flexible than
Number()as it parses partial numeric strings
Conclusion
The parseFloat() function is essential for converting string representations of decimal numbers to actual floating-point values. It's particularly useful when dealing with user input or data from external sources.
Advertisements
