자바 스크립트 : 숫자의 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
보시다시피 저는 :
amount및 모두에서 소수 자릿수를 센다 .percent- 지수 표기법을 사용하여
amount및 둘 다를percent정수로 변환 - 적절한 끝 값을 결정하는 데 필요한 지수 표기법을 계산합니다.
- 최종 값 계산
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
'Program Club' 카테고리의 다른 글
| JSP EL 문자열 연결 (0) | 2020.10.20 |
|---|---|
| R의 파일이 아닌 문자열 값에서 읽기 위해 read.csv를 사용하는 방법이 있습니까? (0) | 2020.10.20 |
| Grand Central Dispatch에서 dispatch_sync 사용 (0) | 2020.10.20 |
| Option [X]의 Scala 컬렉션을 X의 컬렉션으로 변환하는 방법 (0) | 2020.10.20 |
| 배열의 Ruby 출력 내용을 쉼표로 구분 된 문자열 Ruby (0) | 2020.10.20 |