parseInt("piss",10);
returns NaNparseInt("12",10);
returns 12parseInt("12 liter bottle of piss",10);
also returns 12
why did they do this? I get that this is how the fictions are supposed to work, but why did they decide this is the correct way to handle parsing numbers out of a string?
It looks at the first characters and determines if they are a number, if not it just returns NaN.
Why?
because when it parses it has a way to exit quickly. Check the first character, is it a number? If not then exit and return NaN. It's an optimization .
Also if it were to parse the whole string looking for a number it would be ambiguous because you can have a string like
"I have the number 10 and also the number 20".
What does this return? 10? 1020? Who knows. You could also send it a string that's 2 GBs long and have everything hang while the browser waits for the routine to parse the whole string.
>>61591357
why not just return nan upon discovering the first non numeric chat though?
>>61591419
char, rather
>>61591419
dumb phoneposter also because what if you have a string like "120 meters"
>>61591466
ok, but why not just enforce numeric only on an input with nan and avoid the whole parsing issue to begin with? I just can't think of a scenario where these functions are better than doing something else.
>>61591357
》because it exits quickly
It would be even faster if it always returned NaN
>>61591781
Because then you can just pass in "150 tomatoes" and get 150.
Because that's how the C atoxx functions work and checking if the entire string is numeric first is slower than just building an integer until you reach a non numeric.
>>61591781
>why not just enforce numeric only
Because that's less useful for no good reason?