user1406951
user1406951

Reputation: 446

converting string to float/number for numerical operations in javascript

I'm having some issues converting a string to a number for numerical calculations in javascript/knockout

I have the following to calculate the total cost of an order in a knockout form

self.totalCost = ko.computed(function() {
   var total = 0;
   for (var i = 0; i < self.itemNumbers().length; i++)
       //somehow convert the price to a number here so then I can add it 
       total += self.itemNumbers()[i].item.price;
   return total;
});

The display shows nothing, however, when I change "return total" to "return i" the total then displays. I'm assuming means the prices are strings and can't be added. When I output the prices in a table they show up as a decimal (such as 19.99) but I'm not sure if they're actually numbers or strings.

edit below

I used parseFloat to convert the values. Now, in the table that outputs the result I used typeof() and it shows number. The result still isn't summing properly.

Is there anything else I can do to check the values as to why they're not summing? Can I check each individual value that's being added?

Upvotes: 1

Views: 5765

Answers (1)

Fergus
Fergus

Reputation: 220

Maybe.. total += Number(self.itemNumbers()[i].item.price);

Upvotes: 3

Related Questions