Converting string to number in javascript/jQuery

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

Been trying to convert the following to number:

相关标签:
9条回答
  • 2021-01-31 13:47

    It sounds like this in your code is not referring to your .btn element. Try referencing it explicitly with a selector:

    var votevalue = parseInt($(".btn").data('votevalue'), 10);
    

    Also, don't forget the radix.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-31 13:51

    var votevalue = $.map($(this).data('votevalue'), Number);

    0 讨论(0)
  • 2021-01-31 13:52

    You can use parseInt(string, radix) to convert string value to integer like this code below

    var votevalue = parseInt($('button').data('votevalue'));
    ​
    

    DEMO

    0 讨论(0)
  • 2021-01-31 13:55

    Although this is an old post, I thought that a simple function can make the code more readable and keeps with jQuery chaining code-style:

    String.prototype.toNum = function(){
        return parseInt(this, 10);
    }
    

    can be used with jQuery:

    var padding_top = $('#some_div').css('padding-top'); //string: "10px"
    var padding_top = $('#some_div').css('padding-top').toNum(); //number: 10`
    

    or with any String object:

    "123".toNum(); //123 (number)`
    
    0 讨论(0)
  • 2021-01-31 13:56

    It sounds like this is referring to something else than you think. In what context are you using it?

    The this keyword is usually only used within a callback function of an event-handler, when you loop over a set of elements, or similar. In that context it refers to a particular DOM-element, and can be used the way you do.

    If you only want to access that particular button (outside any callback or loop) and don't have any other elements that use the btn-info class, you could do something like:

    parseInt($(".btn-info").data('votevalue'), 10);
    

    You could also assign the element an ID, and use that to select on, which is probably a safer way, if you want to be sure that only one element match your selector.

    0 讨论(0)
提交回复
热议问题