Converting string to number in javascript/jQuery

后端 未结 9 1860
攒了一身酷
攒了一身酷 2021-01-31 13:08

Been trying to convert the following to number:

9条回答
  •  时光说笑
    2021-01-31 13:50

    For your case, just use:

    var votevalue = +$(this).data('votevalue');
    

    There are some ways to convert string to number in javascript.

    The best way:

    var str = "1";
    var num = +str; //simple enough and work with both int and float
    

    You also can:

    var str = "1";
    var num = Number(str); //without new. work with both int and float
    

    or

    var str = "1";
    var num = parseInt(str,10); //for integer number
    var num = parseFloat(str); //for float number
    

    DON'T:

    var str = "1";
    var num = new Number(str);  //num will be an object. typeof num == 'object'
    

    Use parseInt only for special case, for example

    var str = "ff";
    var num = parseInt(str,16); //255
    
    var str = "0xff";
    var num = parseInt(str); //255
    

提交回复
热议问题