In JavaScript doing a simple shipping and handling calculation

前端 未结 6 704
清歌不尽
清歌不尽 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:45

    you can easily convert a string to a number

    http://www.javascripter.net/faq/convert2.htm

    basically JS provides parseInt and parseFloat methods...

    0 讨论(0)
  • 2021-01-14 23:48

    A bit of redundant multiplication, but your problem is that the numbers that are being inputted are treated as strings, not numbers. You have to convert them to floating point numbers:

    var price = parseFloat(window.prompt("What is the purchase price?", 0));
    var shipping = calculateShipping(price);
    var total = price + shipping;
    
    function calculateShipping(price)
    {
      if (price <= 25)
      {
       return 1.5;
      } else {
        return price / 10
      }
    }
    
    window.alert("Your total is $" + total + ".");
    
    0 讨论(0)
  • 2021-01-14 23:51

    See my answer to the s/o question "Javascript adding two numbers incorrectly".

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-15 00:00
    var price = parseFloat(window.prompt("What is the purchase price?", 0)); 
    var shipping = calculateShipping(price); 
    var total = price + shipping; 
    function calculateShipping(price){ 
      var num = new Number(price);
      if (num <= 25){  
        return 1.5; 
      } else{  
        return num * 10 / 100 
      } 
    } 
    window.alert("Your total is $" + total + "."); 
    

    This should do it for you.

    0 讨论(0)
  • 2021-01-15 00:07

    Actually, you need to cast your text results into float values using parseFloat()

    http://www.w3schools.com/jsref/jsref_parseFloat.asp

    0 讨论(0)
提交回复
热议问题