计算百分比Javascript

esp*_*fee 8 html javascript argument-passing percentage

我有一个关于javascript逻辑的问题,我用它来获取文本字段中两个输入的百分比.这是我的代码:

    var pPos = $('#pointspossible').val();
    var pEarned = $('#pointsgiven').val();

    var perc = ((pEarned/pPos) * 100).toFixed(3);
    $('#pointsperc').val(perc);
Run Code Online (Sandbox Code Playgroud)

出于某种原因,如果我的输入是600和200,我的结果假设是33.333但我得到3.333.如果我硬编码我的值,这很好.如果有人可以帮助我,我很感激.提前致谢.

Bru*_*sma 19

你可以用它

function percentage(partialValue, totalValue) {
   return (100 * partialValue) / totalValue;
} 
Run Code Online (Sandbox Code Playgroud)

用于计算课程进度基数在其活动中的百分比的示例.

const totalActivities = 10;
const doneActivities = 2;

percentage(doneActivities, totalActivities) // Will return 20 that is 20%
Run Code Online (Sandbox Code Playgroud)

  • 请注意:如果“partialValue = 0”且“totalValue = 0”,这将返回“NaN” (9认同)

小智 13

尝试:

const result = Math.round((data.expense / data.income) * 100)
Run Code Online (Sandbox Code Playgroud)


Vik*_*ash 9

它似乎有效:

HTML:

 <input type='text' id="pointspossible"/>
<input type='text' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>
Run Code Online (Sandbox Code Playgroud)

JavaScript:

    $(function(){

    $('#pointspossible').on('input', function() {
      calculate();
    });
    $('#pointsgiven').on('input', function() {
     calculate();
    });
    function calculate(){
        var pPos = parseInt($('#pointspossible').val()); 
        var pEarned = parseInt($('#pointsgiven').val());
        var perc="";
        if(isNaN(pPos) || isNaN(pEarned)){
            perc=" ";
           }else{
           perc = ((pEarned/pPos) * 100).toFixed(3);
           }

        $('#pointsperc').val(perc);
    }

});
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/vikashvverma/1khs8sj7/1/


Sam*_*uca 9

要得到一个数的百分比,我们需要乘以所需的百分比百分比。在实践中,我们将有:

function percentage(percent, total) {
    return ((percent/ 100) * total).toFixed(2)
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

const percentResult = percentage(10, 100);
// print 10.00
Run Code Online (Sandbox Code Playgroud)

.toFixed() 对于货币格式是可选的。

  • toFixed() 会将大小写值键入字符串中。 (2认同)

Abr*_*dez 5

很酷(难以阅读)的一行行:

const percentage = ~~((pointsGiven / pointsPossible) * 100);
Run Code Online (Sandbox Code Playgroud)

~~是相同的Math.round()

尝试一下:

const pointsPossible = 600;
const pointsGiven = 200;

const percentage = ~~((pointsGiven / pointsPossible) * 100);

console.log(`Percentage: %${percentage}`)
Run Code Online (Sandbox Code Playgroud)