How do I convert String to Float in Javascript Core?

4

I've always been curious to know how conversion from string to float actually works in , so I would like to receive a complete and detailed response explaining what javascript does internally at the time of conversion to produce the result.

    
asked by anonymous 21.12.2017 / 13:56

1 answer

1

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

Specification (Translation) of the algorithm

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

  • Let inputString be toString
  • ReturnIfAbrupt note: The term abrupt (abrupt) completion refers to any conclusion with the value type other than the normal
  • Let trimmedString be a substring of inputString consisting of the leftmost code unit other than StrWhiteSpaceChar and all code units to right of the code unit. (In other words, remove the whitespace). If inputString does not contain any type of unit of code, let trimmedString be an empty string.
  • If neither trimmedString nor any trimmedString prefix satisfies the StrDecimalLiteral syntax, return NaN
  • Let numberString be the longest prefix of trimmedString , which can be trimmedString , which satisfies the syntax of a StrDecimalLiteral
  • Let mathFloat be MV of numberString
  • If mathFloat = 0 , then

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

    b. Return +0

  • Return the numeric value to mathFloat

    NOTE: parseFloat may interpret only the main part of string as a numeric value; it ignores any unit of code that can not be interpreted as part of the notation of a decimal literal, and no indication is given when some unit of code has been ignored.

  • The algorithm specifies calling other native functions in your flow, such as trim() , for example.

        
    21.12.2017 / 15:33