[removed] calculate x% of a number

后端 未结 10 1803
-上瘾入骨i
-上瘾入骨i 2020-12-12 15:07

I am wondering how in javascript if i was given a number (say 10000) and then was given a percentage (say 35.8%)

how would I work out how much that is (eg 3580)

相关标签:
10条回答
  • 2020-12-12 15:31
    var number = 10000;
    var result = .358 * number;
    
    0 讨论(0)
  • 2020-12-12 15:31

    It may be a bit pedantic / redundant with its numeric casting, but here's a safe function to calculate percentage of a given number:

    function getPerc(num, percent) {
        return Number(num) - ((Number(percent) / 100) * Number(num));
    }
    
    // Usage: getPerc(10000, 25);
    
    0 讨论(0)
  • 2020-12-12 15:34

    If you want to pass the % as part of your function you should use the following alternative:

    <script>
    function fpercentStr(quantity, percentString)
    {
        var percent = new Number(percentString.replace("%", ""));
        return fpercent(quantity, percent);
    }
    
    function fpercent(quantity, percent)
    {
        return quantity * percent / 100;
    }
    document.write("test 1:  " + fpercent(10000, 35.873))
    document.write("test 2:  " + fpercentStr(10000, "35.873%"))
    </script>
    
    0 讨论(0)
  • 2020-12-12 15:35

    This is what I would do:

    // num is your number
    // amount is your percentage
    function per(num, amount){
      return num*amount/100;
    }
    
    ...
    <html goes here>
    ...
    
    alert(per(10000, 35.8));
    
    0 讨论(0)
提交回复
热议问题