[removed] calculate x% of a number

后端 未结 10 1837
-上瘾入骨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:30

    In order to fully avoid floating point issues, the amount whose percent is being calculated and the percent itself need to be converted to integers. Here's how I resolved this:

    function calculatePercent(amount, percent) {
        const amountDecimals = getNumberOfDecimals(amount);
        const percentDecimals = getNumberOfDecimals(percent);
        const amountAsInteger = Math.round(amount + `e${amountDecimals}`);
        const percentAsInteger = Math.round(percent + `e${percentDecimals}`);
        const precisionCorrection = `e-${amountDecimals + percentDecimals + 2}`;    // add 2 to scale by an additional 100 since the percentage supplied is 100x the actual multiple (e.g. 35.8% is passed as 35.8, but as a proper multiple is 0.358)
    
        return Number((amountAsInteger * percentAsInteger) + precisionCorrection);
    }
    
    function getNumberOfDecimals(number) {
        const decimals = parseFloat(number).toString().split('.')[1];
    
        if (decimals) {
            return decimals.length;
        }
    
        return 0;
    }
    
    calculatePercent(20.05, 10); // 2.005
    

    As you can see, I:

    1. Count the number of decimals in both the amount and the percent
    2. Convert both amount and percent to integers using exponential notation
    3. Calculate the exponential notation needed to determine the proper end value
    4. Calculate the end value

    The usage of exponential notation was inspired by Jack Moore's blog post. I'm sure my syntax could be shorter, but I wanted to be as explicit as possible in my usage of variable names and explaining each step.

提交回复
热议问题