views:

738

answers:

4
var price     = $('#addprice').val();
var pass      = $('#pass').val();
var total     = $('#totalprice').attr('value')
var left      = $('#leftquota').attr('value')
var balance   = $('#balance').attr('value')
var tprice    = total + price;   // total price
var bprice    = balance + price; // balance price
var unitprice = bprice / left;   // unit price

$('#totalprice').text(tprice);
$('#balance').text(bprice);
$('#unitprice').text(unitprice);

JQuery just treats total, left, balance, tprice, bprice, unitprice,etc. as strings, but actually there are decimals rather than strings. When I apply parseInt() to them, they all become integers, which are not what I want. How to conduct arithmetic operations? The operands are decimals.

I use parseFloat(); but it is the same. The operation of var tprice=total+price; just literally conjugates two decimals(strings) together.

$('#add_price').click(function(){
    var price=$('#addprice').val();
    var pass=$('#pass').val();
    var total=$('#totalprice').attr('value')
     var left=$('#leftquota').attr('value')
     var balance=$('#balance').attr('value')
     total=parseFloat(total);
     left=parseFloat(left);
     balance=parseFloat(balance);
     var tprice=total+price;
     var bprice=balance+price;
     var unitprice=bprice/left;

     $('#totalprice').text(tprice);
     $('#balance').text(bprice);
     $('#unitprice').text(unitprice);
+1  A: 

Have you tried parseFloat()?

documentation

Kaze no Koe
+2  A: 

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

example of usage:

var tprice = parseFloat(total) + parseFloat(price);
Anwar Chandra
This problem has been resolved. Thank you.
Steven
+2  A: 

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()
stereofrog
A: 

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

Kamarey