问题
I'm trying to multiply the quantity and the price for each item for calculating the total, but I'm getting an error in my alert.
$.each(data.items, function(index, d){
var calcultest = d.price * d.qty;
alert(calcultest)
});
回答1:
Use parseFloat
to convert string to Float
$.each(data.items, function(index, d){
var Price = d.price.replace(",",".");
var calcultest = parseFloat(Price) * parseFloat(d.qty);
alert(calcultest.toString().replace(".",","));
});
FIDDLE
回答2:
Can you try this,
$.each(data.items, function(index, d){
var Price = d.price;
Price = Price.replace(",",".");
var calcultest = parseInt(Price) * parseInt(d.qty);
alert(calcultest);
});
回答3:
If you want to create simple calculators with Javascript I would recommend you to take a look at “Appizy”.
It converts instantly a spreadsheet into a standalone web calculation tool (HTML+CSS+JAVASCRIPT). You don’t need to hardcode the whole interface and calculation formulas!
Just create your working calculator with Open- or LibreOffice and then use Appizy.
I hope it can help. Best, Nicolas
来源:https://stackoverflow.com/questions/21075595/javascript-calculate-quantity-price