In JavaScript doing a simple shipping and handling calculation

前端 未结 6 762
清歌不尽
清歌不尽 2021-01-14 23:39

I am having trouble with a simple JavaScript calculation. My document is supposed to add $1.50 to an order if it is $25 or less, or add 10% of the order if it is more then $

6条回答
  •  我在风中等你
    2021-01-14 23:55

    Using parseFloat will help you:

    var price = parseFloat(window.prompt("What is the purchase price?", 0))
    var shipping = parseFloat(calculateShipping(price));
    var total = price +shipping;
    function calculateShipping(price){
    if (price <= 25){
     return 1.5;
    }
    else{
     return price * 10 / 100
    }
    }
    window.alert("Your total is $" + total + ".");
    

    See it working at: http://jsfiddle.net/e8U6W/

    Also, a little-known put more performant way of doing this would be simply to -0:

    var price =window.prompt("What is the purchase price?", 0) - 0;
    

    (See: Is Subtracting Zero some sort of JavaScript performance trick?)

    Be sure to comment this, though as its not as obvious to those reading your code as parseFloat

提交回复
热议问题