JavaScript 四捨五入、無條件捨去、無條件進位

Math.round() 四捨五入

Math.round(3.14) // 3
Math.round(5.49999) // 5
Math.round(5.5) // 6
Math.round("5.50001") // 6
Math.round(-5.49999) // -5
Math.round(-5.5) // -5
Math.round(-5.50001) // -6
Math.round(18.62645 * 10) / 10 // 18.6
Math.round(18.62645 * 100) / 100 // 18.63
Math.round(18.62645 * 1000) / 1000 // 18.626

Math.floor() 最大整數

取小於這個數的最大整數

Math.floor(3.14) // 3
Math.floor(5.4) // 5
Math.floor(-5.4) // -6
Math.floor("-5.5") // -6

Math.ceil() 最小整數

取大於這個數的最小整數

Math.ceil(3.14) // 4
Math.ceil(5.4) // 6
Math.ceil(-5.4) // -5
Math.ceil("-5.5") // -5

JavaScript 四捨五入線上測試

4Math.round(n)Math.floor(n)Math.ceil(n)

帶小數的四捨五入

var roundDecimal = function (val, precision) {
  return Math.round(Math.round(val * Math.pow(10, (precision || 0) + 1)) / 10) / Math.pow(10, (precision || 0));
}
roundX(18.62645, 2) // 18.63
roundX(18.62645, 3) // 18.626
roundX(18.62645, 4) // 18.6265

數字千分位

function FormatNumber(n) {
  n += "";
  var arr = n.split(".");
  var re = /(\d{1,3})(?=(\d{3})+$)/g;
  return arr[0].replace(re, "$1,") + (arr.length == 2 ? "." + arr[1] : "");
}

JavaScript 數字千分位線上測試

798,736.325Examination

數學函數

Math.abs() 絕對值

絕對值(正值)取參數的絕對值。參數可以是數值亦可以是一個「數值」的字串。

Math.round(3.14) // 3
Math.abs("-12") // 12
Math.abs("-0012") // 12
Math.abs(-12) // 12
Math.abs("00.032") // 0.032
Math.abs("24-5") // NaN
Math.abs("Hello") // NaN