Reputation: 2339
I'm having a problem when executing parseFloat()
- I don't understand why it produces the following outputs:
document.write(parseFloat("6e2") + "<br />"); //output is 600 why?
document.write(parseFloat("6b2") + "<br />"); //output is 6 why?
document.write(parseFloat("6c2") + "<br />"); //output is 6 why?
Could you tell me how the script is working?
Upvotes: 4
Views: 3849
Reputation: 21
parseFloat()
function determines if the first character in the specified string is a number. If it is number then it parses the string until it reaches the end of the number, and it returns the number as a number, not as a string.
so parseFloat("6b2") returns 6.
so parseFloat("6c2") returns 6.
Upvotes: 2
Reputation: 83366
6e2
produces 600 because it's treating your input as scientific notation.
6e2 == 6 x 102 == 600
The other two produce 6 because parseFloat
parses the 6, then gets to input it isn't able to convert to a number, so it stops, and returns the result found so far.
Per MDN:
parseFloat is a top-level function and is not associated with any object.
parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.
If the first character cannot be converted to a number, parseFloat returns NaN.
For arithmetic purposes, the NaN value is not a number in any radix. You can call the isNaN function to determine if the result of parseFloat is NaN. If NaN is passed on to arithmetic operations, the operation results will also be NaN.
Upvotes: 13
Reputation: 572
For the first one, it is because it treats e as an exponent symbol (^)
The other two are only 6 because it ignores the rest once the numbers have ended
Upvotes: 0