source

JavaScript 연산, 소수점 2자리 반올림

bestscript 2022. 11. 13. 19:36

JavaScript 연산, 소수점 2자리 반올림

다음과 같은 JavaScript 구문이 있습니다.

var discount = Math.round(100 - (price / listprice) * 100);

이 값은 정수로 반올림됩니다.소수점 두 자리로 결과를 반환하려면 어떻게 해야 하나요?

메모 - 3자리 정밀도가 중요한 경우 "Edit 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://stackoverflow.com/a/32605063/1726511이라는 답을 찾았습니다.그것은 제가 시도했던 모든 테스트에서 잘 작동하는 것 같습니다.

단, 한 가지 사소한 수정이 필요합니다.상기에 링크된 답변의 함수는 1로 반올림할 때 정수를 반환하기 때문에 예를 들어 99.004는 가격을 표시하는 데 적합하지 않은 99.00 대신 99.00을 반환합니다.

Edit 3 - 실제 반환 시 toFixed가 여전히 일부 숫자를 망치고 있는 것 같습니다.이 최종 편집은 효과가 있는 것 같습니다.정말 많은 재작업이군!

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(digits);
    if (negative) {
        n = (n * -1).toFixed(digits);
    }
    return n;
}

바이올린: https://jsfiddle.net/3Lbhfy5s/79/

단항 플러스를 사용하여 MDN에 기재되어 있는 수치로 문자열을 변환하는 경우.

예를 들어 다음과 같습니다.+discount.toFixed(2)

함수 Math.round() 및 .toFixed()는 가장 가까운 정수로 반올림합니다.소수점을 처리하고 Math.round()의 경우 "multiply and divide" 메서드 또는 .toFixed()의 경우 파라미터를 사용하면 잘못된 결과를 얻을 수 있습니다.예를 들어, Math.round(1.005 * 100) / 100을 사용하여 1.005를 반올림하려고 하면 1.01의 정답이 아닌 .toFixed(2)를 사용하여 1.00의 결과가 나옵니다.

다음을 사용하여 이 문제를 해결할 수 있습니다.

Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2');

.toFixed(2)를 추가하여 원하는 소수점 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/

대안

프로토타입을 사용하여 Number에 반올림 함수를 추가할 수 있습니다.여기에 .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/

2개의 소수점을 사용하여 결과를 얻으려면 다음과 같이 하십시오.

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을 자릿수의 제곱에 곱한 것입니다.다음은 타이프 스크립트에서 사용하는 간단한 기능입니다.

function roundToXDigits(value: number, digits: number) {
    value = value * Math.pow(10, digits);
    value = Math.round(value);
    value = value / Math.pow(10, digits);
    return value;
}

또는 플레인 javascript:

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)문자열을 반환하면 항상 소수점 2자리 숫자가 표시됩니다.0으로 하다마지막 0을 억제하려면 다음 절차를 수행합니다.

var discount = + ((price / listprice).toFixed(2));

편집: 방금 Firefox 35.0.1에서 버그로 보이는 것을 발견했습니다.즉, 위의 내용이 NaN에 값을 부여할 수 있습니다.
드드로로 i to to to to to to to로 .

var discount = Math.round(price / listprice * 100) / 100;

소수점 이하 2자리까지의 숫자가 표시됩니다.3 월 1000 월
OP는 항상 소수점 이하 2자리를 요구하지만 Firefox에서 toFixed()가 고장난 경우 먼저 수정해야 합니다.
https://bugzilla.mozilla.org/show_bug.cgi?id=1134388 를 참조해 주세요.

가장 빠른 방법 - toFixed()보다 빠릅니다.

소수점 2개

x      = .123456
result = Math.round(x * 100) / 100  // result .12

소수점 이하 3자리

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)

다음은 작업 예시입니다.

var value=200.2365455;
result=Math.round(value*100)/100    //result will be 200.24

소수점 이하 자리까지 반올림을 처리하려면 코드 두 줄이 있는 함수로 대부분의 요구에 충분합니다.여기 몇 가지 샘플 코드가 있습니다.



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

언급URL : https://stackoverflow.com/questions/15762768/javascript-math-round-to-two-decimal-places