0

Possible Duplicate:
Is JavaScript’s Math broken?

from this question: get all the input value and make an addition

there is a promotion:

buy 1 each price is 14.37, buy 10 the price is 13.28, buy 20 each price is 10.78.....

now i want to do a counter.http://down123.xxmn.com/count.htm

the counter write the whole price.now, there is something wrong with my code.

if i fill 5 in an input box, then fill 5 in another input box. the whole price isn't 132.8. why?

if i remove a number in an input box, the whole price doesn't change. thank you

the code:

var $inputs = jQuery('.liste_couleur_qty li input');
$inputs.keyup(function() {
   var result = 0;
   $inputs.each(function(){
     result += parseInt(this.value, 10);
   });
   var JsonData =[{"price_id":"1","website_id":"0","price_qty":1,"price":"14.37"},
 {"price_id":"2","website_id":"0","price_qty":10,"price":"13.28"},
 {"price_id":"3","website_id":"0","price_qty":20,"price":"10.78"}, 
  {"price_id":"3","website_id":"0","price_qty":50,"price":"9.23"},
   {"price_id":"3","website_id":"0","price_qty":100,"price":"7.91"}
 ]
   var sorted = JsonData.sort(function(a,b){return a.price_qty - b.price_qty;});

var i=0;
while(i < sorted.length && sorted[i].price_qty <= result){i++;} 

var price = sorted[i-1].price;

   price= price*result;

   jQuery('#qtyvalue').html("Total price is " + price);    
});

now, when the qty is 9, the right price is 9*14.37. but my counter is not right.

Community
  • 1
  • 1
stackoverflow002
  • 329
  • 1
  • 3
  • 10

1 Answers1

0

The answer you are looking for is a method called .toFixed()

Try changing the last line that sets your price to

jQuery('#qtyvalue').html("Total price is " + price.toFixed(2));

and that should work.


Update:

When you empty any text box, your code stops working since the value is '' rather than 0, and can't be added. Update the 5th line of the code to this:

result += parseInt((this.value === '' ? 0 : this.value), 10);
Abhilash
  • 1,610
  • 9
  • 19