我在http://css-tricks.com/multi-product-quantity-based-order-form/
找到了一个JS脚本一旦我实现了它,乘法就不正确了。这是我正在处理的页面:http://www.trueliteinc.com/index.php/carrabbas-order-form/
如果您将“15”作为第二个项目的数量,则总计为38.8499999而不是38.85美元。为什么?我该如何解决这个问题?
这是我认为正在成倍增加的功能:
function calcTotalPallets() {
var totalPallets = 0;
$(".num-pallets-input").each(function() {
var thisValue = parseFloat($(this).val());
if ( (IsNumeric(thisValue)) && (thisValue != '') ) {
totalPallets += parseInt(thisValue);
};
});
$("#total-pallets-input").val(totalPallets).toFixed(2);
}
我的整个代码可以在http://jsfiddle.net/2aFCs/3/
找到非常感谢
答案 0 :(得分:2)
你在错误的事情上打电话给toFixed
。它应该是:
$("#total-pallets-input").val(totalPallets.toFixed(2));
答案 1 :(得分:0)
如果您对使用资金感兴趣,正如整篇评论中所说的那样,建议您将整体和分数计算为整数,以避免浮点数出现精度误差。一个简单的例子是简单地分离整体和美分,并有一个方法为你做计算:
var Money = (function(){
function Money(qty) {
this.whole = 0;
this.cents = 0;
this.add(qty);
}
Money.prototype.calc = function() {
while (this.cents > 100) {
this.cents -= 100;
this.whole += 1;
}
return this;
};
Money.prototype.add = function(qty) {
var parts = qty.split('.');
this.whole += Number(parts[0]);
this.cents += Number(parts[1]);
return this.calc();
};
Money.prototype.toString = function() {
return this.whole +'.'+ this.cents;
};
return Money;
}());
var m = new Money('90.75').add('50.43');
console.log(m); //=> {whole: 141, cents: 18}
console.log(m.toString()); //=> "141.18"
答案 2 :(得分:0)
我实际上想要通过并清理所有代码......但没有时间,所以你的问题就在你的小提琴的第192行。它应该是:
var rowTotal = (numPallets * multiplier).toFixed(2); //it was missing the .toFixed(2)