How to conduct arithmetic operations in JQuery?

前端 未结 5 1713
天命终不由人
天命终不由人 2021-01-03 14:04
var price     = $(\'#addprice\').val();
var pass      = $(\'#pass\').val();
var total     = $(\'#totalprice\').attr(\'value\')
var left      = $(\'#leftquota\').attr         


        
相关标签:
5条回答
  • 2021-01-03 14:23

    you can use parseFloat for this case. it will return float value

    example of usage:

    var tprice = parseFloat(total) + parseFloat(price);
    
    0 讨论(0)
  • 2021-01-03 14:27

    Have you tried parseFloat()?

    documentation

    0 讨论(0)
  • 2021-01-03 14:27

    use parseFloat, parseInt, or just place a + before string, if you sure it contains a number:

    var text = "123.456";
    var number = +text; // now 'number' is Number, and not String
    

    Also something tells me that this should work faster than parseInt or parseFloat.

    Another way to use Number object:

    var text = "123.456";
    var number = Number(text);
    

    But this is the slowest way.

    More info: http://www.jibbering.com/faq/faq_notes/type_convert.html#tcNumber

    0 讨论(0)
  • 2021-01-03 14:30

    Another option is to extend jQuery to be able to read numbers directly from form elements

    jQuery.fn.numVal = function() {
        return parseFloat(this.val()) || 0;
    }
    
       ....
    
      var price=$('#addprice').numVal();
      var pass=$('#pass').numVal()
    
    0 讨论(0)
  • 2021-01-03 14:35

    i was looking for a solution too , and i saw a lot of questions here that doesn't work (even this one) in case someone wondering like me , here is my working solutiuon :

    $("#apport").keyup( 
    function(){
    var apport = parseFloat($("#apport").val());
    var montant = parseFloat($("#montant-financer").val());
    var moinmontant = parseFloat(montant) - parseFloat(apport);     
    $("#montant-financer").val(moinmontant);    
    }
    );
    

    All the id's selector are input

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