Program Club

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

proclub 2020. 10. 20. 18:47
반응형

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


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

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


var result = (35.8 / 100) * 10000;

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


백분율을 100으로 나눈 값 (0과 1 사이의 백분율)을 숫자로

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도 예외는 아닙니다.


var number = 10000;
var result = .358 * number;

어려운 길 (학습 목적) :

var number = 150
var percent= 10
var result = 0
for (var index = 0; index < number; index++) {
   const calculate = index / number * 100
   if (calculate == percent) result += index
}
return result

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

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. 지수 표기법을 사용하여 amount둘 다를 percent정수로 변환
  3. 적절한 끝 값을 결정하는 데 필요한 지수 표기법을 계산합니다.
  4. 최종 값 계산

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.


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

참고URL : https://stackoverflow.com/questions/4372902/javascript-calculate-x-of-a-number

반응형