Hone logo
Hone
Problems

Robust Float Parsing in JavaScript

Parsing floating-point numbers from strings is a common task in web development and data processing. However, JavaScript's built-in parseFloat() function can sometimes produce unexpected results due to its lenient parsing behavior. This challenge asks you to create a function that reliably parses floating-point numbers from strings, handling various formats and edge cases gracefully.

Problem Description

You are tasked with creating a JavaScript function called parseSafeFloat that takes a string as input and returns a floating-point number. The function should adhere to the following requirements:

  • Successful Parsing: If the input string represents a valid floating-point number (e.g., "3.14", "-2.718", "10", "0.5"), the function should return the corresponding floating-point number.
  • Whitespace Handling: The function should trim leading and trailing whitespace from the input string before parsing.
  • Invalid Input: If the input string cannot be parsed as a floating-point number (e.g., "abc", "1.2.3", "hello world"), the function should return NaN.
  • Exponential Notation: The function should correctly parse numbers in exponential notation (e.g., "1.23e+4", "4.56E-2").
  • Empty String: If the input string is empty after trimming whitespace, the function should return NaN.
  • Null/Undefined Input: If the input is null or undefined, the function should return NaN.

Examples

Example 1:

Input: "  3.14  "
Output: 3.14
Explanation: The input string is trimmed, and then parsed as the float 3.14.

Example 2:

Input: "-2.718"
Output: -2.718
Explanation: A negative float is parsed correctly.

Example 3:

Input: "abc"
Output: NaN
Explanation: The input string is not a valid float, so NaN is returned.

Example 4:

Input: "1.23e+4"
Output: 12300
Explanation: Exponential notation is correctly parsed.

Example 5:

Input: ""
Output: NaN
Explanation: An empty string results in NaN after trimming.

Example 6:

Input: null
Output: NaN
Explanation: Null input results in NaN.

Constraints

  • The input string can contain any characters.
  • The function must handle both positive and negative floating-point numbers.
  • The function must be performant enough to handle a large number of parsing operations without significant delays. While micro-optimizations aren't required, avoid excessively complex or inefficient algorithms.
  • The function should not throw any exceptions.

Notes

Consider using JavaScript's built-in parseFloat() function as a starting point, but be mindful of its limitations and potential for unexpected behavior. Think about how to handle edge cases and invalid input gracefully. Regular expressions could be used, but are not strictly necessary and may impact performance. Focus on clarity and robustness.

Loading editor...
javascript