appdesigns
appdesigns

Reputation: 134

Why parseInt does not ignore first symbol, or character of an integer value

Trying to change a string value to integer in jQuery. Is there a workaround of having parseInt disregard the symbol $ and rather capture the integer/number 90.00?

var price =("$90.00");
var i = (price);
var j = parseInt(i);
console.log(j)

expecting an output of : 90.00

output NAN

Upvotes: 1

Views: 1548

Answers (1)

Dekel
Dekel

Reputation: 62626

If you check here you will see that:

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

Since $ is not a valid numerical character - parseInt will ignore it and all the following characters, and you will actually have parseInt on empty string - parseInt(''), which results in NaN.

console.log(parseInt(''));

If you know that your strings contains only the dollar-sign and you want to remove it you can use the replace function to do that:

const price = "$90.0";
console.log(parseInt(price.replace(/\$/, '')));

Upvotes: 3

Related Questions