Функція Math.round()
повертає значення числа заокруглене до найближчого цілого.
Джерело цих інтерактивних прикладів зберігається у репозиторії на GitHub. Якщо ви маєте бажання зробити свій внесок у проект інтерактивних прикладів - будь ласка, зклонуйте репозиторій https://github.com/mdn/interactive-examples та пришліть нам pull request.
Синтаксис
Math.round(x)
Параметри
x
- Число.
Повернуте значення
Значення отриманого числа, округлене до найближчого цілого.
Опис
Якщо дробова частина числа більша або рівна 0.5, аргумент буде округлено до найближчого більшого цілого. Якщо дробова частина числа менша 0.5, аргумент буде округлено до найближчого меншого цілого. Якщо дробова частина рівна 0.5, то аргумент буде округлено до найближчого цілого в напрямку +∞. Зверніть увагу, що функція round() відрізняється від багатьох мов, які часто приводять цей випадок до наступного цілого числа, віддаленого від нуля (маємо інший результат у випадку від'ємних чисел з дробовою частиною рівною 0.5).
Оскільки round() - це статичний метод Math, ви завжди використовуєте його як Math.round (), а не як метод об'єкта Math, який ви створили (Math не має конструктора).
Приклади
Math.round( 20.49); // 20
Math.round( 20.5); // 21
Math.round( 42 ); // 42
Math.round(-20.5); // -20
Math.round(-20.51); // -21
Десяткове округлення
// 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
PHP-Like rounding Method
The code below can be used to add your own version of Math.round to your own namespace which takes a precision parameter. Unlike Decimal rounding in the example above, this performs no conversion to and from strings, and the precision parameter works same way as PHP and Excel whereby a positive 1 would round to 1 decimal place and -1 would round to the tens.
var myNamespace = {};
myNamespace.round = function(number, precision) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = Math.round(tempNumber);
return roundedTempNumber / factor;
};
myNamespace.round(1234.5678, 1); // 1234.6
myNamespace.round(1234.5678, -1); // 1230
Cпецифікації
Специфікація | Статус | Коментар |
---|---|---|
ECMAScript 1st Edition (ECMA-262) | Standard | Початкове визначення. Впроваджено в JavaScript 1.0. |
ECMAScript 5.1 (ECMA-262) The definition of 'Math.round' in that specification. |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Math.round' in that specification. |
Standard | |
ECMAScript (ECMA-262) The definition of 'Math.round' in that specification. |
Living Standard |
Сумісність браузерів
BCD tables only load in the browser
Таблиця сумісності на цій сторінці сформована автоматично із структурованих даних. Якщо ви маєте бажання зробити свій внесок до цих даних - будь-ласка, ось репозиторій https://github.com/mdn/browser-compat-data, надішліть нам свій pull request.