In javascript you can manipulate numbers by rounding them to the nearest integer using several functions. Below are some functions along with the explanations:
Math.round()
Example:
Math.round(4.5); // returns 5
Math.round(4.6); // returns 5
Math.round(4.4); // returns 4
Math.round(-4.4); // returns -4
Math.ceil()
Example:
Math.ceil(4.2); // returns 5
Math.ceil(-4.4); // returns -4
Math.ceil(-7.8); // returns -7
Math.floor()
Example:
Math.floor(4.7); // returns 4
Math.floor(-4.4); // returns -5
Math.floor(-7.8); // returns -8
Math.floor(7.8); // returns 7
Math.trunc()
Example:
Math.trunc(4.7); // returns 4
Math.trunc(-4.4); // returns -4
Math.trunc(-7.8); // returns -7
Math.trunc(7.8); // returns 7
Function | Description | Example Input | Output |
---|---|---|---|
Math.round | Rounds up to the nearest integer | 4.2 | 5 |
-4.2 | -4 | ||
Math.ceil | Rounds up to the next integer | 4.2 | 5 |
-4.2 | -4 | ||
Math.floor | Rounds a number downwards to the nearest integer | 4.2 | 5 |
-4.2 | -4 | ||
Math.trunc | Truncates (removes) the decimal parts of the number, returning just the integer part. | 4.2 | 5 |
-4.2 | -4 |
Created with ❤️ using Next.js & Tailwind CSS