String To Number Confusion

Why does parseInt("-1000-500-75-33") return -1000?

Shouldn't it return the sum of those numbers: -1608

How can I get the string "-1000-500-75-33" to return as the sum of those numbers?

Answers 1

  • Since they are in a string, ParseInt does not parse the whole string, just finds the first applicable number from the start & returns it. If the start of the string cannot be parsed, it returns NaN

    parseInt("-1000NOT_NUMBER") = -1000
    parseInt("test-1000`) = NaN

    You have to use eval function to do what you want, that evaluates given string as if it were a command entered into the console;

    eval("-1000-500-75-33") = -1608

Related Articles