Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String variable to int in javascript?

What is the correct way to convert value of String variable to int/numeric variable? Why is bcInt still string and why does isNaN return true?

bc=localStorage.getItem('bc');
var bcInt=parseInt(bc,10);
var bcInt2=1;
console.log("bc------------>" +bc +" isNaN:" +isNaN(bc)); //isNaN returns true
console.log("bcInt------------>" +bcInt +" isNaN:" +isNaN(bcInt)); //isNaN returns true

bcInt2// isNaN returns false
like image 996
Sami Avatar asked Jan 16 '23 19:01

Sami


1 Answers

parseInt returns a number only if you pass it a number as first character.

Examples:

parseInt( 'a', 10 ); // NaN
parseInt( 'a10', 10 ); // NaN
parseInt( '10a', 10 ); // 10
parseInt( '', 10 ); // NaN
parseInt( '10', 10 ); // 10

Also, you may take a look at the + operator if you want to get strings that are only numbers.

+'a'; // NaN
+'a10'; // NaN
+'10a'; // NaN
+''; // 0, that's tricky
+'10'; // 10

Edit: According to your comment, I've tested parseInt:

parseInt( '08-20 19:41:02.880', 10 ); // 8

You're doing something else wrong. parseInt returns everything till it's not a number. If the first isn't a number (or it doesn't find any number), it returns NaN.

like image 176
Florian Margaine Avatar answered Jan 20 '23 15:01

Florian Margaine