programing

javascript에서 숫자를 반올림하는 방법은 무엇입니까?

bestcode 2023. 1. 21. 09:49
반응형

javascript에서 숫자를 반올림하는 방법은 무엇입니까?

예를 들어 라운딩을 해야 합니다.6.688689로.6.7하지만 그것은 항상 나를 보여준다.7.

내 방법:

Math.round(6.688689);
//or
Math.round(6.688689, 1);
//or 
Math.round(6.688689, 2);

하지만 결과는 항상 같다.7내가 뭘 잘못하고 있지?

Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

사용하다toFixed()기능.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

Upd(2019-10)아래의 Rece Daniels 코드 덕분에 npm 패키지로 구성된 일련의 기능을 사용할 수 있게 되었습니다(확인해 보십시오).


MDN 예에서 도우미 기능을 사용할 수 있습니다.유연성이 향상됩니다.

Math.round10(5.25, 0);  // 5
Math.round10(5.25, -1); // 5.3
Math.round10(5.25, -2); // 5.25
Math.round10(5, 0);     // 5
Math.round10(5, -1);    // 5
Math.round10(5, -2);    // 5

갱신(2019-01-15)MDN 문서에는 이 도우미 기능이 없는 것 같습니다.다음은 예를 들어 백업입니다.

// 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
> +(6.688687).toPrecision(2)
6.7

A NumberJavaScript의 오브젝트에는 필요한 작업을 수행하는 메서드가 있습니다.그 방법은 입니다.

와 마찬가지로.toFixed(1)결과를 문자열로 변환하고 다시 숫자로 변환해야 합니다.사용 완료+프레픽스를 입력합니다.

심플한 벤치마크:

number = 25.645234 typeof number
50000000 x number.toFixed(1) = 25.6 typeof string / 17527ms
50000000 x +(number.toFixed(1)) = 25.6 typeof number / 23764ms
50000000 x number.toPrecision(3) = 25.6 typeof string / 10100ms
50000000 x +(number.toPrecision(3)) = 25.6 typeof number / 18492ms
50000000 x Math.round(number*10)/10 = 25.6 typeof number / 58ms
string = 25.645234 typeof string
50000000 x Math.round(string*10)/10 = 25.6 typeof number / 7109ms

사용뿐만 아니라toFixed()하지만 또한ceil()그리고.floor()플로트에서 다음 기능을 사용할 수 있습니다.

function roundUsing(func, number, prec) {
    var tempnumber = number * Math.pow(10, prec);
    tempnumber = func(tempnumber);
    return tempnumber / Math.pow(10, prec);
}

작성:

> roundUsing(Math.floor, 0.99999999, 3)
0.999
> roundUsing(Math.ceil, 0.1111111, 3)
0.112

업데이트:

다른 방법은 다음과 같습니다.

Number.prototype.roundUsing = function(func, prec){
    var temp = this * Math.pow(10, prec)
    temp = func(temp);
    return temp / Math.pow(10, prec)
}

작성:

> 6.688689.roundUsing(Math.ceil, 1)
6.7
> 6.688689.roundUsing(Math.round, 1)
6.7
> 6.688689.roundUsing(Math.floor, 1)
6.6

확장 라운드 기능:

function round(value, precision) {
  if (Number.isInteger(precision)) {
    var shift = Math.pow(10, precision);
    // Limited preventing decimal issue
    return (Math.round( value * shift + 0.00000000000001 ) / shift);
  } else {
    return Math.round(value);
  }
} 

출력 예:

round(123.688689)     // 123
round(123.688689, 0)  // 123
round(123.688689, 1)  // 123.7
round(123.688689, 2)  // 123.69
round(123.688689, -2) // 100
round(1.015, 2) // 1.02

이하를 참조해 주세요.

var original = 28.59;

var result=Math.round(original*10)/10돌려드립니다.28.6

이게 네가 원하는 것이길..

.toLocaleString() 대신 로케일, 그룹화, 통화 포맷, 표기법 등 다양한 옵션을 사용할 수 있습니다.몇 가지 예:


소수점 1로 반올림하고 플로트를 반환합니다.

const n = +6.688689.toLocaleString('fullwide', {maximumFractionDigits:1})
console.log(
  n, typeof n
)


소수점 2개로 반올림하고 지정된 기호가 있는 통화로 포맷하고 쉼표 그룹화를 사용합니다.

console.log(
  68766.688689.toLocaleString('fullwide', {maximumFractionDigits:2, style:'currency', currency:'USD', useGrouping:true})   
)


로케일 통화 형식:

console.log(
  68766.688689.toLocaleString('fr-FR', {maximumFractionDigits:2, style:'currency', currency:'EUR'})   
)


소수점 이하 3으로 반올림하고 0을 강제로 표시합니다.

console.log(
  6.000000.toLocaleString('fullwide', {minimumFractionDigits:3})
)


비율에 대한 백분율 스타일입니다.입력 * 100 (% 기호 포함)

console.log(
  6.688689.toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'})
)

toFixed()가 동작하지 않는 경우 매우 좋은 솔루션이 있습니다.

function roundOff(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

roundOff(10.456,2) //output 10.46
float(value,ndec);
function float(num,x){
this.num=num;
this.x=x;
var p=Math.pow(10,this.x);
return (Math.round((this.num).toFixed(this.x)*p))/p;
}
+((6.688689 * (1 + Number.EPSILON)).toFixed(1)); // 6.7
+((456.1235 * (1 + Number.EPSILON)).toFixed(3)); // 456.124

이 기능이 도움이 될 것 같아요.

 function round(value, ndec){
    var n = 10;
    for(var i = 1; i < ndec; i++){
        n *=10;
    }

    if(!ndec || ndec <= 0)
        return Math.round(value);
    else
        return Math.round(value * n) / n;
}


round(2.245, 2) //2.25
round(2.245, 0) //2

node.discontext에 있는 경우 mathjs를 시도할 수 있습니다.

const math = require('mathjs')
math.round(3.1415926, 2) 
// result: 3.14
Math.round((6.688689 + Number.EPSILON) * 10) / 10

https://stackoverflow.com/a/11832950/2443681에서 도난당한 솔루션

이것은 거의 모든 부동값에 대해 작동해야 합니다.10진수를 강제하지는 않습니다.이것이 요구 사항이었는지는 명확하지 않다.사용하는 것보다 빨라야 합니다.toFixed()다른 답변에 대한 코멘트를 바탕으로 다른 문제도 있습니다.

필요한 10진수 정밀도로 반올림할 수 있는 편리한 유틸리티 함수:

const roundToPrecision = (value, decimals) => {
  const pow = Math.pow(10, decimals);
  return Math.round((value + Number.EPSILON) * pow) / pow;
};

아래 기능이 도움이 될 것 같습니다.

function roundOff(value,round) {
   return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
}

사용방법:roundOff(600.23458,2);600.23

답변에 대한 사소한 수정:

function roundToStep(value, stepParam) {
   var step = stepParam || 1.0;
   var inv = 1.0 / step;
   return Math.round(value * inv) / inv;
}

roundToStep(2.55, 0.1) = 2.6
roundToStep(2.55, 0.01) = 2.55
roundToStep(2, 0.01) = 2

지금 Browserify를 사용하고 있다면, 다음과 같이 시도해 볼 필요가 있습니다.roundTo 매우 유용한 NPM lib

언급URL : https://stackoverflow.com/questions/9453421/how-to-round-float-numbers-in-javascript

반응형