source

자바스크립트에서 숫자를 10분의 1로 반올림하는 방법?

nicesource 2023. 11. 5. 14:44
반응형

자바스크립트에서 숫자를 10분의 1로 반올림하는 방법?

자바스크립트를 이용해서 숫자를 반올림하고 싶습니다.숫자는 통화이므로 다음 예제와 같이 반올림합니다(소수점 2개).

  • 192.168 => 192.20
  • 192.11 => 192.20
  • 192.21 => 192.30
  • 192.26 => 192.30
  • 192.20 => 192.20

자바스크립트를 이용하여 이를 달성하는 방법은?기본으로 제공되는 자바스크립트 기능은 표준논리에 따라 숫자를 반올림합니다(반올림하려면 5보다 작음).

/**
 * @param num The number to round
 * @param precision The number of decimal places to preserve
 */
function roundUp(num, precision) {
  precision = Math.pow(10, precision)
  return Math.ceil(num * precision) / precision
}

roundUp(192.168, 1) //=> 192.2

일반적인 반올림은 약간의 조정을 통해 작동합니다.

Math.round(price * 10)/10

통화 형식을 유지하려면 Number 방법을 사용하면 됩니다..toFixed()

(Math.round(price * 10)/10).toFixed(2)

이렇게 하면 String이 되겠지만 =)

조금 늦었지만, 이 목적을 위해 재사용 가능한 자바스크립트 함수를 만들 수 있습니다.

// Arguments: number to round, number of decimal places
function roundNumber(rnum, rlength) { 
    var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    return newnumber;
}

함수를 다음과 같이 부릅니다.

alert(roundNumber(192.168,2));

TheEye의 답변에 근접했지만, 저는 그것을 가능하게 하기 위해 작은 것을 바꿉니다.

var num = 192.16;
    
console.log(    Math.ceil(num * 10) / 10    );

OP는 두 가지를 기대합니다.
A. 상위 10위까지 반올림하고,
B. 100위 안에 0을 표시하는 것(통화에 대한 전형적인 필요).

두 가지 요건을 모두 충족하려면 위의 각 항목에 대해 별도의 방법이 필요할 것으로 보입니다.다음은 수리야키란의 제안된 답변을 기반으로 하는 접근 방식입니다.

//Arguments: number to round, number of decimal places.

function roundPrice(rnum, rlength) {
    var newnumber = Math.ceil(rnum * Math.pow(10, rlength-1)) / Math.pow(10, rlength-1);
    var toTenths = newnumber.toFixed(rlength);
    return toTenths;
}

alert(roundPrice(678.91011,2)); // returns 679.00
alert(roundPrice(876.54321,2)); // returns 876.60

참고: 이 솔루션은 음수와 지수로 매우 다른 결과를 가져옵니다.

이 답변과 매우 유사한 두 답변을 비교하려면 다음 두 가지 접근법을 참조하십시오.첫 번째 것은 단순히 평소의 100분의 1로 반올림하고, 두 번째 것은 단순히 가장 가까운 100분의 1(더 큰)로 반올림합니다.

function roundNumber(rnum, rlength) { 
    var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    return newnumber;
}

alert(roundNumber(678.91011,2)); // returns 678.91

function ceilNumber(rnum, rlength) { 
    var newnumber = Math.ceil(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    return newnumber;
}

alert(ceilNumber(678.91011,2)); // returns 678.92

좋아요, 이것은 답변이 되었지만, 당신이 그를 부르는 나의 답변을 보고 싶어할지도 모른다고 생각했습니다.math.pow()한 번 기능합니다.건조하게 하는 걸 좋아하는 것 같아요.

function roundIt(num, precision) {
    var rounder = Math.pow(10, precision);
    return (Math.round(num * rounder) / rounder).toFixed(precision)
};

이 모든 것을 하나로 묶는 것 같습니다.교체하다Math.round()와 함께Math.ceil()반올림 대신에 반올림하는 것이 OP가 원했던 것입니다.

이 함수는 십진법에 반올림수를 포함하지 않습니다.

function limitDecimal(num,decimal){
     return num.toString().substring(0, num.toString().indexOf('.')) + (num.toString().substr(num.toString().indexOf('.'), decimal+1));
}

@AndrewMarshall answer를 오랫동안 사용해 왔지만 몇 가지 엣지 케이스를 발견했습니다.다음 테스트는 통과되지 않습니다.

equals(roundUp(9.69545, 4), 9.6955);
equals(roundUp(37.760000000000005, 4), 37.76);
equals(roundUp(5.83333333, 4), 5.8333);

이제 라운드업이 올바르게 동작하도록 하기 위해 사용하는 방법은 다음과 같습니다.

// Closure
(function() {
  /**
   * Decimal adjustment of a number.
   *
   * @param {String}  type  The type of adjustment.
   * @param {Number}  value The number.
   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
   * @returns {Number} The adjusted value.
   */
  function decimalAdjust(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
      return NaN;
    }
    // If the value is negative...
    if (value < 0) {
      return -decimalAdjust(type, -value, exp);
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  }

  // Decimal round
  if (!Math.round10) {
    Math.round10 = function(value, exp) {
      return decimalAdjust('round', value, exp);
    };
  }
  // Decimal floor
  if (!Math.floor10) {
    Math.floor10 = function(value, exp) {
      return decimalAdjust('floor', value, exp);
    };
  }
  // Decimal ceil
  if (!Math.ceil10) {
    Math.ceil10 = function(value, exp) {
      return decimalAdjust('ceil', value, exp);
    };
  }
})();

// Round
Math.round10(55.55, -1);   // 55.6
Math.round10(55.549, -1);  // 55.5
Math.round10(55, 1);       // 60
Math.round10(54.9, 1);     // 50
Math.round10(-55.55, -1);  // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1);      // -50
Math.round10(-55.1, 1);    // -60
Math.round10(1.005, -2);   // 1.01 -- compare this with Math.round(1.005*100)/100 above
Math.round10(-1.005, -2);  // -1.01
// Floor
Math.floor10(55.59, -1);   // 55.5
Math.floor10(59, 1);       // 50
Math.floor10(-55.51, -1);  // -55.6
Math.floor10(-51, 1);      // -60
// Ceil
Math.ceil10(55.51, -1);    // 55.6
Math.ceil10(51, 1);        // 60
Math.ceil10(-55.59, -1);   // -55.5
Math.ceil10(-59, 1);       // -50

출처 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

자바스크립트로 가치를 반올림하는 가장 간단한 방법

let num = 5.56789;
let n = num.toFixed(2);
console.log(n); //output 5.57

parseInt는 항상 반올림합니다 soo...

console.log(parseInt(5.8)+1);

do parseInt()+1

언급URL : https://stackoverflow.com/questions/5191088/how-to-round-up-a-number-to-a-precision-of-tenths-in-javascript

반응형