簡體   English   中英

如何在Javascript中對數字進行四舍五入?

[英]How to round up a number in Javascript?

我想使用 Javascript 對數字進行四舍五入。 由於數字是貨幣,我希望它像這些示例中那樣四舍五入(2 個小數點):

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

如何使用 Javascript 實現這一點? 內置 Javascript 函數將根據標准邏輯對數字進行四舍五入(小於和大於 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

有點晚了,但是,可以為此目的創建一個可重用的 javascript 函數:

// 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));

正常的四舍五入只需稍作調整即可:

Math.round(price * 10)/10

如果要保留貨幣格式,可以使用 Number 方法.toFixed()

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

雖然這將使它成為一個字符串 =)

非常接近TheEye 的答案,但我改變了一點讓它工作:

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

OP期望兩件事:
A. 向上取整到十分之一,並且
B. 在百分之一處顯示零(貨幣的典型需求)。

滿足這兩個要求似乎需要對上述每個要求單獨的方法。 這是一種基於 suryakiran 建議答案的方法:

//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

重要提示:此解決方案會產生與負數和指數數截然不同的結果。

為了比較這個答案和兩個非常相似的答案,請參閱以下兩種方法。 第一個簡單地四舍五入到最接近的百分之一,第二個簡單地四舍五入到最接近的百分之一(更大)。

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.ceil() 替換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 回答很長時間了,但發現了一些邊緣情況。 以下測試未通過:

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

這是在javascript中匯總您的價值的最簡單方法

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

parseInt 總是四舍五入...

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

做 parseInt()+1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM