How is the conversion from String to Float done in Javascript Core?

Asked

Viewed 97 times

4

I’ve always been curious to know how the conversion really works string for float internally in the , so I would like to receive a full and detailed answer explaining what javascript does internally at the time of conversion to produce the result obtained.

  • 1

    To specification Ecmascript defines the exact algorithm used by parseFloat, whose exact implementation depends on the engine

1 answer

1

The function responsible for making the conversion is the parseFloat and is not associated with any object. Number.parseFloat is the same used by parseFloat. To ECMA determines how the algorithm works, but the implementation can be different depending on the Engine Javascript.

Specification (Translation) of the algorithm

The function parseFloat produces a numerical value dictated by the interpretation of the content of the string literal decimal. When the function parseFloat is called with an argument string, the following steps are taken:

  1. Let inputString was toString

  2. ReturnIfAbrupt note: The term abrupt (sudden) conclusion refers to any conclusion with the type value other than normal

  3. Let trimmedString be a substring of inputString consisting of the leftmost unit of code other than Strwhitespacechar and all code units to the right of the code unit. (In other words, remove whitespace). If inputString does not contain any kind of code unit, let trimmedString be an empty string.

  4. If not even trimmedString nor any prefix of trimmedString satisfies the syntax of Strdecimalliteral, return Nan

  5. Let numberString be the longest prefix of trimmedString, which may be trimmedString which satisfies the syntax of a Strdecimalliteral

  6. Let mathFloat be mv of numberString

  7. If mathFloat=0, then

    a. If the first unit of trimmedString is "-", returne -0

    b. Return +0

  8. Return the numeric value to mathFloat

    NOTE: parseFloat perhaps only interprets the main part of the string as a numerical value; it ignores any unit of code that cannot be interpreted as part of the notation of a decimal literal, and no indication is given when any unit of code has been ignored.


The algorithm specifies the call of other native functions in its stream, such as trim() for example.

  • Good answer, but I particularly found it confusing to understand the functioning, maybe it would be better to expose the implementation code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.