소수점 이하 두 자리로 반올림되는 자바 스크립트 수학
이 질문에는 이미 답변이 있습니다.
다음과 같은 JavaScript 구문이 있습니다.
var discount = Math.round(100 - (price / listprice) * 100);
정수로 올림합니다. 소수점 이하 두 자리로 결과를 어떻게 반환합니까?
참고-3 자리 정밀도가 중요한 경우 편집 4 참조
var discount = (price / listprice).toFixed(2);
toFixed는 소수점 이하 2 자리 이상의 값에 따라 올림 또는 내림됩니다.
예 : http://jsfiddle.net/calder12/tv9HY/
설명서 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
편집 -다른 사람들이 언급했듯이 결과를 문자열로 변환합니다. 이것을 피하려면 :
var discount = +((price / listprice).toFixed(2));
편집 2- 주석에서 언급 했듯이이 함수는 정밀하게 실패합니다. 예를 들어 1.005의 경우 1.01 대신 1.00을 반환합니다. 이 정도의 정확성이 중요하다면이 답변을 찾았습니다 : https : //.com/a/32605063/1726511 내가 시도한 모든 테스트에서 잘 작동하는 것 같습니다.
하나의 작은 수정이 필요하지만 위의 답변의 함수는 1로 반올림 할 때 정수를 반환하므로 예를 들어 99.004는 99.00 대신 99를 반환하므로 가격을 표시하는 데 적합하지 않습니다.
편집 3- 실제 수익률에 고정 된 것으로 보이지만 여전히 숫자를 망쳐 놓은 것처럼 보입니다.이 최종 편집은 작동하는 것으로 보입니다. 이런 많은 재 작업!
var discount = roundTo((price / listprice), 2);
function roundTo(n, digits) {
if (digits === undefined) {
digits = 0;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
var test =(Math.round(n) / multiplicator);
return +(test.toFixed(digits));
}
여기에 바이올린 예제를 참조하십시오 : https://jsfiddle.net/calder12/3Lbhfy5s/
편집 4- 너희들이 나를 죽이고있다. 반올림을 수행하기 전에 음수를 양수로 돌리고 결과를 반환하기 전에 다시 돌리는 것이 더 쉬운 이유를 파헤 치지 않고 음수에서는 편집 3이 실패합니다.
function roundTo(n, digits) {
var negative = false;
if (digits === undefined) {
digits = 0;
}
if( n < 0) {
negative = true;
n = n * -1;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
n = (Math.round(n) / multiplicator).toFixed(2);
if( negative ) {
n = (n * -1).toFixed(2);
}
return n;
}
피들 : https://jsfiddle.net/3Lbhfy5s/79/
단항 더하기를 사용하여 MDN에 설명 된대로 문자열을 숫자 로 변환하는 경우 .
예를 들면 다음과 같습니다.+discount.toFixed(2)
Math.round () 및 .toFixed () 함수는 가장 가까운 정수로 반올림하기위한 것입니다. 소수점을 처리하고 Math.round ()에 대해 "multiply and 나누기"메서드를 사용하거나 .toFixed ()에 대한 매개 변수를 사용하면 잘못된 결과가 나타납니다. 예를 들어 Math.round (1.005 * 100) / 100을 사용하여 1.005를 반올림하면 1.01의 정답을 얻는 대신 1과 1.00을 .toFixed (2)를 사용하여 얻을 수 있습니다.
다음을 사용하여이 문제를 해결할 수 있습니다.
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2');
.toFixed (2)를 추가하여 원하는 소수점 이하 두 자리를 구하십시오.
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2').toFixed(2);
반올림을 처리하는 함수를 만들 수 있습니다.
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
예 : https://jsfiddle.net/k5tpq3pd/36/
대체
프로토 타입을 사용하여 숫자에 반올림 함수를 추가 할 수 있습니다. 숫자 대신 문자열을 반환하므로 .toFixed ()를 추가하지 않는 것이 좋습니다.
Number.prototype.round = function(decimals) {
return Number((Math.round(this + "e" + decimals) + "e-" + decimals));
}
다음과 같이 사용하십시오.
var numberToRound = 100 - (price / listprice) * 100;
numberToRound.round(2);
numberToRound.round(2).toFixed(2); //Converts it to string with two decimals
예 https://jsfiddle.net/k5tpq3pd/35/
출처 : http://www.jacklmoore.com/notes/rounding-in-javascript/
소수점 이하 두 자릿수로 결과를 얻으려면 다음과 같이하십시오.
var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;
반올림 할 값에 100을 곱하여 처음 두 자리를 유지 한 다음 100으로 나누어 실제 결과를 얻습니다.
내가 찾은 가장 좋고 간단한 해결책은
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // 1.01
사용해보십시오 discount.toFixed(2);
내가 본 가장 좋은 방법은 10을 곱한 자릿수의 수에 곱한 다음 Math.round를 수행 한 다음 마지막으로 10의 자릿수를 나누는 것입니다. typescript에서 사용하는 간단한 함수는 다음과 같습니다.
function roundToXDigits(value: number, digits: number) {
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
또는 일반 자바 스크립트 :
function roundToXDigits(value, digits) {
if(!digits){
digits = 2;
}
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
허용되는 답변에 약간의 변형이 있습니다. toFixed(2)
문자열을 반환하며 항상 소수점 이하 두 자리를 얻습니다. 이들은 0 일 수 있습니다. 최종 0을 억제하려면 다음과 같이하십시오.
var discount = + ((price / listprice).toFixed(2));
편집 : 방금 Firefox 35.0.1에서 버그로 보이는 것을 발견했습니다. 위에서 NaN에 일부 값을 줄 수 있음을 의미합니다.
코드를 다음으로 변경했습니다.
var discount = Math.round(price / listprice * 100) / 100;
이것은 소수점 이하 두 자리까지의 숫자를 제공합니다. 세 개를 원하면 1000을 곱하고 나눕니다.
OP는 항상 소수점 이하 두 자리를 원하지만 Firefox에서 toFixed ()가 깨지면 먼저 수정해야합니다.
참조 https://bugzilla.mozilla.org/show_bug.cgi?id=1134388를
가장 빠른 방법 -toFixed ()보다 빠름 :
두 가지 결정
x = .123456
result = Math.round(x * 100) / 100 // result .12
세 가지 결정
x = .123456
result = Math.round(x * 1000) / 1000 // result .123
function round(num,dec)
{
num = Math.round(num+'e'+dec)
return Number(num+'e-'+dec)
}
//Round to a decimal of your choosing:
round(1.3453,2)
소수점 이하 자릿수로 반올림을 처리하려면 대부분의 경우 2 줄의 코드가있는 함수로 충분합니다. 재생할 샘플 코드는 다음과 같습니다.
var testNum = 134.9567654;
var decPl = 2;
var testRes = roundDec(testNum,decPl);
alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);
function roundDec(nbr,dec_places){
var mult = Math.pow(10,dec_places);
return Math.round(nbr * mult) / mult;
}
function discoverOriginalPrice(discountedPrice, salePercentage) {
var originalPrice = discountedPrice / (1 - (salePercentage * .01));
return +originalPrice.toFixed(2);
}
다음은 실제 예입니다
var value=200.2365455;
result=Math.round(value*100)/100 //result will be 200.24
참고 URL : https://stackoverflow.com/questions/15762768/javascript-math-round-to-two-decimal-places
'Programing' 카테고리의 다른 글
REST API 모범 사례 : 매개 변수 값 목록을 입력으로 승인하는 방법 (0) | 2020.02.26 |
---|---|
WordPress에 대한 올바른 파일 권한 (0) | 2020.02.26 |
확인란 켜기 / 끄기 (0) | 2020.02.25 |
HTTPS를 통한 HttpClient를 사용하여 모든 인증서 신뢰 (0) | 2020.02.25 |
Android에서 ListViews 사이의 줄을 어떻게 제거합니까? (0) | 2020.02.25 |