簡體   English   中英

計算訂單總額:應用折扣

[英]Calculating the total of an order: Applying discounts

我正在使用javascript開發在線訂單。 我幾乎可以使用它,但是如果選擇的項目超過5個,我想做的是給予12.5%的折扣。 到目前為止,如果選擇了多個項目,我已經設法獲得了折扣。 這是我的代碼:

var totalItems = 0

// Run through the form fields to check for any filled fields
for (var i=0; i<juiceForm.length; i++)
{

    n=0;
    juicetotal = 0;
    itemQuantity = Number(parseInt(juiceForm[i].value)); // convert field value to a number

    itemQuantity = parseInt(juiceForm[i].value);
    if (isNaN(itemQuantity)) 
    {
        itemQuantity = 0; // If the form field value is not a number, make it zero
    }

    // count the total number of juices selected
    totalItems = totalItems += Number(parseInt(juiceForm[i].value));

    if (totalItems >= 5 || itemQuantity >= 5 || (totalItems + itemQuantity) >= 5)
    {
        juiceTotal = (juiceTotal+(itemQuantity * juicePrice[i]))*0.875;
    }
    else 
    {
    // Multiply the quantity by the item price and update the order total   
        juiceTotal = juiceTotal+(itemQuantity * juicePrice[i]);
    }
}

我遇到麻煩的地方是,如果選擇了多個項目,總共提供了5個以上的項目,則計算結果是錯誤的。 例如,如果我有5箱蘋果汁(20英鎊)和1箱橙子(22英鎊),並有12.5%的折扣,我應該總共得到106.75英鎊,但我得到95.81英鎊。

我不確定是否犯了明顯的錯誤。 誰能給我有關我做錯事情的任何建議?

也許您會想到這一點(未經測試,將其作為偽代碼)

var totalItems = 0
var juiceTotal = 0;
for (var i=0; i<juiceForm.length; i++)
{
    var itemQuantity = parseInt(juiceForm[i].value);
    if (isNaN(itemQuantity)) 
    {
        itemQuantity = 0;
    }
    totalItems += itemQuantity;
    juiceTotal += (juicePrice[i]*itemQuantity);  
}

if (totalItems >= 5)
    juiceTotal *= 0.875;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM