Rounding Numbers with Google Apps Script

To round a number, you mainly have these 3 functions:

  • Math.round()
  • Math.floor()
  • Math.ceil()

Round to the Nearest Whole Number

Math.round(12); // 12
Math.round(12.34); // 12
Math.round(12.5); // 13
Math.round(12.871); // 13
Math.round(-12.34); // -12
Math.round(-12.5); // -12
Math.round(-12.871); // -13

Round Down to the Nearest Whole Number

Math.floor(12); // 12
Math.floor(12.34); // 12
Math.floor(12.5); // 12
Math.floor(12.871); // 12
Math.floor(-12.34); // -13
Math.floor(-12.5); // -13
Math.floor(-12.871); // -13

Round Up to the Nearest Whole Number

Math.ceil(12); // 12
Math.ceil(12.34); // 13
Math.ceil(12.5); // 13
Math.ceil(12.871); // 13
Math.ceil(-12.34); // -12
Math.ceil(-12.5); // -12
Math.ceil(-12.871); // -12

Round to a Specified Number of Decimal Places

Example for rounding to 2 decimal places:

let number = 12.3456789;
number = Math.round(number * 100) / 100;
console.log(number); // Returns: 12.35

Round to 0.05

let number = 47.771;
number = Math.round(number * 20) / 20;
console.log(number); // Returns: 47.75

Or:

let number = 47.771;
number = Math.round(number / 0.05) * 0.05;
console.log(number); // Returns: 47.75