round

JavaScript, Math

Rounds a number to a specified amount of digits.

  • Use Math.round() and template literals to round the number to the specified number of digits.
  • Omit the second argument, decimals, to round to an integer.
const round = (n, decimals = 0) => 
  Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
round(1.005, 2); // 1.01

Recommended snippets

  • arithmeticProgression

    JavaScript, Math

    Creates an array of numbers in the arithmetic progression, starting with the given positive integer and up to the specified limit.

  • digitize

    JavaScript, Math

    Converts a number to an array of digits, removing its sign if necessary.

  • geometricProgression

    JavaScript, Math

    Initializes an array containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step. Returns an error if step equals 1.