Math.round()

ES1+

Returns the value rounded to the nearest integer, with exact halves rounded toward positive infinity: Math.round(2.5) is 3, but Math.round(-2.5) is -2. This "half up toward +∞" rule differs from the half-to-even (banker's) rounding used in many financial and scientific contexts.

Syntax

Math.round(x)

Parameters

x number

A number

Return Value

number

The value of the number rounded to the nearest integer

Examples

JavaScript
console.log(Math.round(4.5));
console.log(Math.round(4.4));
console.log(Math.round(-4.5));
Output:
// 5 4 -4

📌 When to Use

Use Math.round() when you want the integer nearest to a value and a consistent, cheap tie-break: converting computed floats into display integers (percentages, star ratings, pixel positions), snapping measurements to whole units, reporting statistics where up-or-down bias does not matter, and quantizing sensor or animation values. Combined with scaling it rounds to fixed decimals, Math.round(x * 100) / 100, though this idiom inherits binary floating-point behavior and needs care for values whose scaled form lands epsilon-below a half (see the mistakes below). Know its tie-break rule before using it near boundaries: halves go toward positive infinity, so 0.5 rounds to 1 while -0.5 rounds to -0, meaning positive and negative datasets are treated asymmetrically at exact halves; statistical aggregation over symmetric data acquires a slight upward bias. When those ties matter, financial ledgers, tax calculations, scientific pipelines, implement the required rule explicitly (half-to-even, half-away-from-zero) or compute in integer minor units where ties cannot occur. For display formatting, prefer Intl.NumberFormat or toFixed at the very edge of the system rather than rounding values you will keep computing with; rounding early then aggregating compounds error.

⚠️ Common Mistakes

Assuming symmetric half-rounding: Math.round(-2.5) is -2, not -3. The rule is "half toward positive infinity", not "half away from zero", so negative halves round up numerically. Ports of algorithms from Java or Python (both round half differently) silently change behavior at ties.

The 1.005 problem: Math.round(1.005 * 100) / 100 yields 1 instead of 1.01, because 1.005 is stored as 1.00499999999999989..., so the scaled value is 100.499..., below the half. This is a property of binary doubles, not of round; fixes include integer cents, or nudging with Number.EPSILON as in Math.round((x + Number.EPSILON) * 100) / 100 (adequate for display, not for ledgers).

Rounding inside a computation chain: rounding each line item, then summing, gives a different total than summing then rounding, and users notice when the invoice footer disagrees with the lines by a cent. Decide where rounding happens (usually once, at the boundary) as policy.

Using Math.round() to generate random integers: Math.round(Math.random() * 10) makes 0 and 10 half as likely as 1-9, because each endpoint captures only half an interval. The uniform recipe is Math.floor(Math.random() * 11).

Expecting toFixed to agree with Math.round: toFixed operates on the exact binary value with its own rules, so (1.005).toFixed(2) is "1.00" while hand-scaled rounding of the same displayed number may differ; never mix the two methods for the same figure in one UI.

Rounding user-entered floats before validation, which can mask out-of-range input (100.4 rounding to 100 passes a max-100 check while the user typed an invalid value); validate the raw input, round for storage or display afterward.

✅ Best Practices

Reserve Math.round() for display and quantization; keep full precision in state and round at the last moment. A roundForDisplay(x, decimals) helper with the EPSILON nudge covers typical UI needs in one tested place.

For money, do not round floats at all: represent amounts as integer minor units (cents), perform integer arithmetic, and format with Intl.NumberFormat({ style: "currency" }), which handles decimals, grouping, and symbols per locale.

When ties must follow a specific standard, implement it explicitly: half-to-even can be written in a few lines or taken from a decimal library (decimal.js, big.js); relying on Math.round's +∞ tie-break in financial code is an audit finding waiting to happen.

Round percentages so they sum to 100 using a largest-remainder pass rather than rounding each share independently; independently rounded shares routinely total 99 or 101 and erode user trust in dashboards.

Document rounding boundaries in APIs: state whether endpoints return rounded or full-precision values, so clients do not re-round (compounding error) or diff against their own differently rounded copies.

⚡ Performance Notes

Math.round() is a single inlined operation, as cheap as floor and ceil, with no allocation; use it freely in render loops, canvas drawing (where integer pixel coordinates also avoid subpixel antialiasing blur, a genuine rendering-performance win), and bulk data processing. The multiply-round-divide idiom for decimals adds two arithmetic ops, still negligible. What can cost real time is the formatting layer often confused with rounding: toFixed and Intl.NumberFormat calls allocate strings and, for Intl, consult locale data, so in large tables cache a single NumberFormat instance and call format() with already-computed numbers. Also note the numeric-precision boundary: above 2^53 (Number.MAX_SAFE_INTEGER) integers lose exactness and rounding questions become meaningless; such magnitudes belong in BigInt, where fractional rounding does not exist by construction.

🌍 Real World Example

Product Rating Display

Star ratings compress messy averages like 4.279 into the tidy figures users scan: this example rounds to the nearest half star by scaling by 2, rounding, and dividing back, the general recipe for rounding to any step, plus a one-decimal numeric label. It also keeps the raw average for tooltips and sorting, illustrating the golden rule that rounding is presentation, not state. The same scale-round-unscale move snaps prices to 0.05 in cash-rounding countries, angles to 15° in design tools, and slider values to their step.

function displayRating(rawRating) {
  const roundedRating = Math.round(rawRating * 2) / 2; // Round to nearest 0.5
  const fullStars = Math.floor(roundedRating);
  const hasHalfStar = roundedRating % 1 !== 0;

  return {
    display: roundedRating.toFixed(1),
    fullStars,
    hasHalfStar,
    emptyStars: 5 - fullStars - (hasHalfStar ? 1 : 0)
  };
}

console.log(displayRating(4.3)); // { display: '4.5', fullStars: 4, hasHalfStar: true, emptyStars: 0 }
console.log(displayRating(3.7)); // { display: '3.5', fullStars: 3, hasHalfStar: true, emptyStars: 1 }

Related Methods