To convert a floating-point number into a whole integer in JavaScript, choose the rounding behavior your logic requires: Math.trunc() strips the fractional part toward zero, Math.floor() rounds down toward negative infinity, Math.ceil() rounds up toward positive infinity, and Math.round() rounds to the nearest integer (halfway cases round toward positive infinity). Always validate that the input is a finite number (Number.isFinite()) before converting so NaN or Infinity does not slip through silently.


1. Truncating vs. Rounding Floating-Point Numbers (Math.trunc, Math.floor, Math.ceil, Math.round)

Use Math.trunc() when you simply want to drop decimals toward zero, and use Math.floor(), Math.ceil(), or Math.round() when directional or nearest-integer rounding matters:

// Convert a float to an integer using explicit rounding mode and finite-number guards
function floatToInteger(value, mode = "trunc") {
  const numeric = typeof value === "number" ? value : Number(value);
  if (!Number.isFinite(numeric)) {
    throw new TypeError("Expected a finite number or numeric string.");
  }

  const operations = Object.freeze({
    trunc: Math.trunc,
    floor: Math.floor,
    ceil: Math.ceil,
    round: Math.round
  });

  const fn = operations[mode] || Math.trunc;
  return fn(numeric);
}

// Example usage:
console.log(floatToInteger(4.9, "trunc")); // 4
console.log(floatToInteger(-4.9, "trunc")); // -4
console.log(floatToInteger(-4.2, "floor")); // -5
console.log(floatToInteger(4.1, "ceil")); // 5
console.log(floatToInteger(4.5, "round")); // 5
  • Explicit rounding semantics: Makes whether -4.9 becomes -4 (trunc) or -5 (floor) obvious to any reader.
  • No input mutation: Returns a new primitive integer without altering any variables or objects.

2. Converting Numeric Strings to Whole Integers with Number.parseInt()

When starting from a string like "42.85px" or "99.9", use Number.parseInt(str, 10) with an explicit radix of 10 to parse leading integer digits—or convert via Number() + Math.trunc() when you want "42.85" to round/truncate cleanly rather than dropping digits after the decimal point:

// Parse a string into a whole integer with radix 10 and explicit guard checks
function stringToInteger(input, { roundDecimal = false } = {}) {
  if (typeof input !== "string" && typeof input !== "number") {
    throw new TypeError("Input must be a string or number.");
  }

  if (typeof input === "number") {
    if (!Number.isFinite(input)) {
      throw new TypeError("Number must be finite.");
    }
    return roundDecimal ? Math.round(input) : Math.trunc(input);
  }

  const trimmed = input.trim();
  if (trimmed === "") {
    throw new Error("Cannot convert an empty string to an integer.");
  }

  if (roundDecimal) {
    const parsedFloat = Number(trimmed);
    if (!Number.isFinite(parsedFloat)) {
      throw new Error(`Invalid numeric string: "${input}"`);
    }
    return Math.round(parsedFloat);
  }

  const parsedInt = Number.parseInt(trimmed, 10);
  if (!Number.isFinite(parsedInt)) {
    throw new Error(`Invalid integer string: "${input}"`);
  }

  return parsedInt;
}

// Example usage:
console.log(stringToInteger("18.75")); // 18
console.log(stringToInteger("18.75", { roundDecimal: true })); // 19
  • Always pass radix 10: Prevents unexpected octal or legacy prefix behavior in parseInt().
  • Distinguishes truncation from rounding: "18.75" becomes 18 with parseInt(..., 10) and 19 when roundDecimal uses Math.round().

3. Common Traps to Avoid

Converting floating-point values into integers in JavaScript frequently hits a few pitfalls:

  • Using bitwise hacks like | 0 or ~~x on large numbers: Bitwise operators coerce values to signed 32-bit integers (-2147483648 to 2147483647), silently wrapping or corrupting numbers outside 32-bit range—prefer Math.trunc() or Math.floor().
  • Calling parseInt() on a floating-point number without converting/rounding first: parseInt(1e-7, 10) converts 1e-7 to "1e-7" internally and returns 1, while parseInt(0.5, 10) returns 0—be explicit with Math.trunc(), Math.floor(), or Math.round().
  • Forgetting Number.isFinite() checks: Math.floor(NaN) is NaN, and passing unvalidated user input can produce NaN downstream if not guarded.

TL;DR: Use Math.trunc(), Math.floor(), Math.ceil(), or Math.round() (and Number.parseInt(str, 10) for integer strings) after guarding with Number.isFinite(), avoiding 32-bit bitwise hacks like | 0 for general integer conversion.