Steven
Steven

Reputation: 19435

How can I work with decimals in javascript?

For the last hour I've tried several different solutions but none have solved my problem.

I have various input fields containing a decimal number (price of product) e.g. 98.00.

Looping through a list of items, I need to add the fields together:

  // Calculate sub-total
  $('.selected_list li.order_line:visible').each(function(){
    var item_cost = $(this).find('input.item_cost').val();
    sub_total = sub_total + item_cost;
  })

How can I add these items and get a result containing two decimals?
My fiddle here: http://jsfiddle.net/EgGUm/

Upvotes: 0

Views: 222

Answers (2)

Kristof Claes
Kristof Claes

Reputation: 10941

You can use parseFloat() to convert the strings. I have updated your Fiddle: http://jsfiddle.net/EgGUm/11/

  // Calculate sub-total
  $('.selected_list li.order_line:visible').each(function(){
    var item_cost = parseFloat($(this).find('input.item_cost').val());
    sub_total = sub_total + item_cost;
  })

Upvotes: 1

Panagiotis
Panagiotis

Reputation: 1567

Use parseFloat:

 var item_cost = parseFloat($(this).find('input.item_cost').val());

More, here

Upvotes: 2

Related Questions