Lodash toInteger: Removing Decimals Without Rounding

The _.toInteger method in the Lodash JavaScript library converts inputs into integers by strictly stripping away fractional decimal values rather than executing standard rounding algorithms. Instead of utilizing functions such as Math.round() or Math.floor(), Lodash normalizes the input to a finite number and executes a remainder-based truncation using the modulo operator. This article explains the underlying source logic of _.toInteger, demonstrating how arithmetic subtraction enforces integer truncation toward zero across both positive and negative values.

The Source Implementation

Lodash defines toInteger through a concise, high-performance function that relies on the internal toFinite helper:

function toInteger(value) {
  const result = toFinite(value);
  const remainder = result % 1;

  return remainder ? result - remainder : result;
}

This implementation bypasses native rounding methods entirely, achieving strict decimal truncation through two distinct steps: input normalization and remainder subtraction.

Step 1: Input Normalization via toFinite

Before any arithmetic manipulation occurs, the input value is passed through toFinite(). This conversion layer handles non-numeric types, edge cases, and boundary constraints:

Once toFinite resolves, the function guarantees a clean, finite floating-point number.

Step 2: Remainder Calculation via Modulo

To isolate the fractional component without invoking rounding logic, Lodash calculates:

const remainder = result % 1;

In JavaScript, the modulo operator (%) returns the remainder of the division between the left operand and the right operand while preserving the sign of the dividend. Dividing any floating-point number by 1 isolates everything past the decimal point:

Step 3: Subtraction and Truncation

After determining the remainder, the function evaluates whether a fractional part exists:

return remainder ? result - remainder : result;

If remainder is non-zero, Lodash subtracts that remainder directly from the original number:

By subtracting the fractional remainder, the number is always shifted toward zero, producing identical behavior to ES6's Math.trunc().

Why Lodash Avoids Standard Rounding Methods

Lodash deliberately avoids Math.round(), Math.floor(), and Math.ceil() because each of these methods shifts fractional values based on magnitude or direction rather than cleanly discarding the decimal: