숫자 (예 : 10000)를받은 다음 백분율 (예 : 35.8 %)을받은 경우 자바 스크립트에서 어떻게해야하는지 궁금합니다.
그게 얼마인지 어떻게 알아낼까요 (예 : 3580)
답변:
var result = (35.8 / 100) * 10000;
( 이 작업 순서 변경에 대해 jball 에게 감사드립니다 . 고려하지 않았습니다).
var, 또는 whitspace 가 필요하지 않다고 말할 수 있지만 읽기가 어렵거나 좋은 코드가 아닐까요? : P
var result = pct / 100 * number;
두 가지 매우 유용한 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>
부동 소수점 문제를 완전히 방지하려면 백분율을 계산하는 금액과 백분율 자체를 정수로 변환해야합니다. 이 문제를 해결 한 방법은 다음과 같습니다.
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및 모두에서 소수 자릿수를 세 십시오.percentamountpercent지수 표기법을 사용하여 및 정수로지수 표기법의 사용은 Jack Moore의 블로그 게시물 에서 영감을 얻었 습니다 . 내 구문이 더 짧을 수 있다고 확신하지만 변수 이름을 사용하고 각 단계를 설명 할 때 가능한 한 명확하게하고 싶었습니다.
var number = 10000;
var result = .358 * number;
var number=10000; alert(number*0.358);