Skip to main content

Command Palette

Search for a command to run...

JavaScript Math Reference

Updated
2 min read
JavaScript Math Reference
T

Just a guy who loves to write code and watch anime.

Basic Rounding Functions

Math.floor(x) -> Always rounds DOWN to nearest integer

Math.floor(4.9); // 4
Math.floor(4.1); // 4
Math.floor(-4.1); // -5 (down means more negative)
Math.floor(-4.9); // -5

Math.ceil(x) -> Always rounds UP to nearest integer

Math.ceil(4.1); // 5
Math.ceil(4.9); // 5
Math.ceil(-4.9); // -4 (up means less negative)
Math.ceil(-4.1); // -4

Math.round(x) -> Rounds to nearest integer (0.5 rounds up)

Math.round(4.4); // 4
Math.round(4.5); // 5
Math.round(4.6); // 5
Math.round(-4.5); // -4
Math.round(-4.6); // -5

Math.trunc(x) -> Removes decimal part (truncates toward zero)

Math.trunc(4.9); // 4
Math.trunc(4.1); // 4
Math.trunc(-4.9); // -4 (toward zero)
Math.trunc(-4.1); // -4

Rounding to Decimal Places

Round to N decimal places:

// Round to 2 decimal places
Math.round(4.567 * 100) / 100; // 4.57
Number((4.567).toFixed(2)); // 4.57

// Round to 1 decimal place
Math.round(4.567 * 10) / 10; // 4.6

Quick Reference

Function4.24.7-4.2-4.7
floor44-5-5
ceil55-4-4
round45-4-5
trunc44-4-4

Memory trick: Floor goes down, ceiling goes up, truncate cuts off decimals, round goes to nearest.