How to convert String variable to int in javascript?

空扰寡人 提交于 2019-12-01 08:22:18

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.

Sami

The answer is that I used localStorage.setItem('bc',JSON.stringify(bc)) and it added double quote to bc because it was in that case already a string and that's why parseInt wasn't working. Value was ""1"".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!