[javascript] 자바 스크립트 : 숫자의 x % 계산

숫자 (예 : 10000)를받은 다음 백분율 (예 : 35.8 %)을받은 경우 자바 스크립트에서 어떻게해야하는지 궁금합니다.

그게 얼마인지 어떻게 알아낼까요 (예 : 3580)



답변

var result = (35.8 / 100) * 10000;

( 이 작업 순서 변경에 대해 jball 에게 감사드립니다 . 고려하지 않았습니다).


답변

백분율을 100으로 나눈 값 (0과 1 사이의 백분율을 구하기 위해) x 숫자로 나눈 값

35.8/100*10000


답변

이것이 내가 할 일입니다.

// num is your number
// amount is your percentage
function per(num, amount){
  return num*amount/100;
}

...
<html goes here>
...

alert(per(10000, 35.8));


답변

두 가지 매우 유용한 JS 함수를 사용합니다.
http://blog.bassta.bg/2013/05/rangetopercent-and-percenttorange/

function rangeToPercent(number, min, max){
   return ((number - min) / (max - min));
}

function percentToRange(percent, min, max) {
   return((max - min) * percent + min);
}


답변

%를 함수의 일부로 전달하려면 다음 대안을 사용해야합니다.

<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>


답변

가장 좋은 것은 균형 방정식을 자연스럽게 암기하는 것입니다.

Amount / Whole = Percentage / 100

일반적으로 하나의 변수가 누락되었습니다.이 경우 Amount입니다.

Amount / 10000 = 35.8 / 100

그런 다음 고등학교 수학 (비율)을 양쪽에서 여러 외부로, 양쪽에서 내부로합니다.

Amount * 100 = 358 000

Amount = 3580

모든 언어와 문서에서 동일하게 작동합니다. JavaScript도 예외는 아닙니다.


답변

부동 소수점 문제를 완전히 방지하려면 백분율을 계산하는 금액과 백분율 자체를 정수로 변환해야합니다. 이 문제를 해결 한 방법은 다음과 같습니다.

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

보시다시피 저는 :

  1. amount및 모두에서 소수 자릿수를 세 십시오.percent
  2. 둘 다 변환 amountpercent지수 표기법을 사용하여 및 정수로
  3. 적절한 끝 값을 결정하는 데 필요한 지수 표기법을 계산합니다.
  4. 최종 값 계산

지수 표기법의 사용은 Jack Moore의 블로그 게시물 에서 영감을 얻었 습니다 . 내 구문이 더 짧을 수 있다고 확신하지만 변수 이름을 사용하고 각 단계를 설명 할 때 가능한 한 명확하게하고 싶었습니다.