KatInterview

Handling IEEE 754 Floating-Point Limits in JavaScript

Math & Bit ManipulationModel answer
EasyModel answerMath & Bit Manipulationjavascriptieee-754numeric-precision

Last updated

Understand JavaScript numeric edge cases, floating-point precision constraints, and how to safely implement custom checks without built-in helpers.

In JavaScript, standard numbers are represented as double-precision 64-bit IEEE 754 floating-point values. Because there is no native distinction between integers and floats at the runtime level, handling values near the bounds of floating-point precision or dealing with implicit type coercion requires careful handling.

Write a technical explanation and implement three standard numeric safety functions from first principles, without using built-in methods like Number.isFinite() or Number.isSafeInteger():

  1. isTrulyNumeric(val): Returns true if val evaluates to a valid, finite number. It should accept valid numeric strings (e.g., "42", "-3.14") while rejecting non-numeric values (null, undefined, booleans, objects, empty strings) and special float values (NaN, Infinity).
  2. isSafeInteger(val): Returns true only if val is a primitive number that is an integer within the range [-(2^53 - 1), 2^53 - 1]. Non-number primitives and numeric strings should return false.
  3. safeAdd(a, b): Performs addition on a and b. If both inputs and the resulting sum are safe integers, it returns the numeric sum. Otherwise, it returns the exact string "Result exceeds safe integer limits".

Example Behaviors

isTrulyNumeric(42);              // true
isTrulyNumeric(" 3.14 ");        // true
isTrulyNumeric("100px");         // false
isTrulyNumeric(NaN);             // false
isTrulyNumeric(null);            // false

isSafeInteger(9007199254740991); // true (2^53 - 1)
isSafeInteger(9007199254740992); // false (2^53)
isSafeInteger("42");             // false

safeAdd(10, 20);                 // 30
safeAdd(9007199254740991, 1);    // "Result exceeds safe integer limits"

Constraints

  • Do not use Number.isFinite, Number.isSafeInteger, isFinite, or isNaN.
  • Demonstrate proper handling of JavaScript coercion quirks without relying on high-level helpers.

Hints

Hint 1

How can you check if a number is finite without `isFinite`? Consider mathematical operations involving non-finite values like `NaN` and `Infinity` (e.g., subtracting a number from itself).

Hint 2

Beware of JavaScript coercion traps with `Number()`: `Number('')`, `Number(null)`, and `Number(false)` all evaluate to `0`.

Hint 3

What is the significand bit-width of an IEEE 754 double, and how does that dictate `2^53 - 1` as the maximum safe integer?