JavaScript: Robust String to Number Conversion
In JavaScript, converting strings to numbers is a fundamental operation, often encountered when dealing with user input, API responses, or data from external sources. This challenge will test your ability to handle various string formats and edge cases accurately, ensuring your conversions are robust and predictable.
Problem Description
Your task is to create a JavaScript function named convertStringToNumber that takes a single argument, inputString, which is expected to be a string. This function should attempt to convert the inputString into a number.
The function should:
- Handle integers (e.g., "123", "-45").
- Handle floating-point numbers (e.g., "123.45", "-0.5").
- Handle numbers represented in scientific notation (e.g., "1e6", "2.5e-3").
- Handle strings that represent hexadecimal numbers (e.g., "0xFF", "0x1A").
- Return
NaN(Not-a-Number) if theinputStringcannot be parsed into a valid number, including empty strings or strings containing only whitespace. - If the input is already a number type, return it as is.
- Trim whitespace from the beginning and end of the
inputStringbefore attempting conversion.
Examples
Example 1:
Input: "12345"
Output: 12345
Explanation: A standard integer string is converted to its numeric representation.
Example 2:
Input: "-98.6"
Output: -98.6
Explanation: A negative floating-point string is converted correctly.
Example 3:
Input: " 1.23e4 "
Output: 12300
Explanation: Whitespace is trimmed, and the string in scientific notation is converted to its numeric value.
Example 4:
Input: "0xFF"
Output: 255
Explanation: A hexadecimal string is parsed and converted to its decimal equivalent.
Example 5:
Input: ""
Output: NaN
Explanation: An empty string cannot be converted to a valid number.
Example 6:
Input: "hello"
Output: NaN
Explanation: A non-numeric string results in NaN.
Example 7:
Input: " "
Output: NaN
Explanation: A string containing only whitespace, after trimming, becomes an empty string and results in NaN.
Example 8:
Input: 42 (number type)
Output: 42
Explanation: If the input is already a number, it should be returned as is.
Constraints
- The input
inputStringwill always be of typestringornumber. - The resulting number should fit within JavaScript's standard
Numbertype limits.
Notes
Consider the built-in JavaScript methods available for string-to-number conversion. Think about how each method handles different formats and potential errors. Trimming whitespace is a crucial first step. Remember that NaN is a special numeric value in JavaScript.