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?
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?
parseInt
will try to get a number starting from the beginning of the string.
Since -
is a valid character to begin a number with, it parses the string until it finds something invalid. The second -
is invalid because no integer can contain an -
inside it, only digits. So it stops there and considers the number to be "finished".
Now, if you want to process the expression, you can use eval
like so:
eval("-1000-500-75-33")
This will return -1608
as expected.
parseInt
will not perform any computations, rather it will try to convert a string into an integer. It returns -1000
because the dash afterwards would not be considered a valid number. If you want to sum all these numbers you could split on the dash, map to Number, then reduce:
var numString = "-1000-500-75-33";
numString.split('-').map(e => Number(e)).reduce((a, b) => a - b);
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
console.log(eval("-1000-500-75-33").toString());
And about type casting: After parsing -1000, which is obviously "negative 1000", It will escape casting as soon as it detect a symbol common between numbers & strings. So parseInt
is seeing "-1000-500-75-33"
as "-1000NotConvertableString"
, So left the remaining away, returning -1000
as the result of type-casting.