Handling IEEE 754 Floating-Point Limits in JavaScript
Math & Bit ManipulationModel answerLast 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():
isTrulyNumeric(val): Returnstrueifvalevaluates 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).isSafeInteger(val): Returnstrueonly ifvalis a primitive number that is an integer within the range[-(2^53 - 1), 2^53 - 1]. Non-number primitives and numeric strings should returnfalse.safeAdd(a, b): Performs addition onaandb. 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, orisNaN. - 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?
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Technical Overview
JavaScript stores all standard numbers as IEEE 754 double-precision 64-bit floating-point values. A 64-bit double allocates:
- 1 bit for the sign ($s$).
- 11 bits for the exponent ($e$).
- 52 bits for the fraction/significand ($m$), yielding 53 bits of precision with the implicit leading 1 bit.
Because of this layout, integers can only be uniquely represented without precision loss up to $2^{53} - 1$ (Number.MAX_SAFE_INTEGER). At $2^{53}$ and above, the least significant bits cannot be stored, leading to loss of precision where consecutive integers map to the exact same floating-point bit pattern (e.g., 2**53 === 2**53 + 1 evaluates to true).
Core Mechanics & Coercion Rules
To solve this task without high-level library functions, we must exploit fundamental runtime behavior:
1. Finiteness Check via Arithmetic Identity
For any finite number $n \in \mathbb{R}$, $n - n = 0$. However:
- $\text{NaN} - \text{NaN} = \text{NaN}$ (and $\text{NaN} \neq 0$)
- $\infty - \infty = \text{NaN}$
- $-\infty - (-\infty) = \text{NaN}$
Thus, for a value $n$ where typeof n === 'number', the condition n - n === 0 accurately filters out NaN, Infinity, and -Infinity.
2. Avoid False Positives in String Coercion
JavaScript's implicit type conversion contains several notorious edge cases:
Number("")evaluates to0.Number(null)evaluates to0.Number(false)evaluates to0.Number([])evaluates to0.
To implement isTrulyNumeric, we must enforce explicit type checks:
- Reject non-string and non-number types immediately.
- Strip whitespace from strings and verify they are not empty before casting with
Number(val). - Use
Number(val)rather thanparseFloat(), becauseparseFloat("100px")returns100, whereasNumber("100px")evaluates toNaN.
3. Strict Integer Verification
To verify if a primitive float is an integer:
- Ensure
Math.floor(val) === val(orval % 1 === 0). - Ensure
Math.abs(val) <= 9007199254740991($2^{53} - 1$).
JavaScript Reference Implementation
const MAX_SAFE_INT = 9007199254740991; // Math.pow(2, 53) - 1
const ERROR_MSG = "Result exceeds safe integer limits";
/**
* Checks if a value is a finite number, or a non-empty string that parses to one.
*/
function isFiniteNum(n) {
return typeof n === "number" && n - n === 0;
}
function isTrulyNumeric(val) {
if (typeof val === "number") {
return isFiniteNum(val);
}
if (typeof val === "string") {
// Exclude empty strings or whitespace-only strings
if (val.trim() === "") return false;
return isFiniteNum(Number(val));
}
return false;
}
/**
* Checks if a value is a primitive number that represents a safe integer.
*/
function isSafeInteger(val) {
return (
isFiniteNum(val) &&
Math.floor(val) === val &&
Math.abs(val) <= MAX_SAFE_INT
);
}
/**
* Adds two numbers safely. Returns an error message if inputs or result violate bounds.
*/
function safeAdd(a, b) {
if (!isSafeInteger(a) || !isSafeInteger(b)) {
return ERROR_MSG;
}
const sum = a + b;
return isSafeInteger(sum) ? sum : ERROR_MSG;
}
Python Verification Port
import math
MAX_SAFE_INT = 2**53 - 1
ERROR_MSG = "Result exceeds safe integer limits"
def _is_finite_num(n):
# Exclude booleans explicitly since bool is a subclass of int in Python
if isinstance(n, bool) or not isinstance(n, (int, float)):
return False
return n - n == 0
def is_truly_numeric(val):
if isinstance(val, str):
if val.strip() == "":
return False
try:
return _is_finite_num(float(val))
except ValueError:
return False
return _is_finite_num(val)
def is_safe_integer(val):
return (
_is_finite_num(val)
and math.floor(val) == val
and abs(val) <= MAX_SAFE_INT
)
def safe_add(a, b):
if not is_safe_integer(a) or not is_safe_integer(b):
return ERROR_MSG
total = a + b
if is_safe_integer(total):
return total
return ERROR_MSG
Complexity Analysis
-
Time Complexity:
isTrulyNumeric: $\mathcal{O}(L)$ where $L$ is the length of the string (due to string trimming and parsing). For numeric inputs, it executes in $\mathcal{O}(1)$ constant time.isSafeInteger: $\mathcal{O}(1)$ basic arithmetic operations.safeAdd: $\mathcal{O}(1)$ constant execution time.
-
Space Complexity:
- $\mathcal{O}(1)$ auxiliary memory across all three operations (ignoring temporary string copies during trimming).
Common Pitfalls & Interview Edge Cases
-0Handling:Math.floor(-0)yields-0, and-0 === -0istrue.Math.abs(-0)is0.-0correctly satisfies all safe integer constraints.- Implicit String Concatenation: If input validation is omitted in
safeAdd, callingsafeAdd("5", 10)would result in"510"instead of performing numeric addition. - Numeric Literals Above $2^{53}$: Writing
safeAdd(9007199254740993, 0)in JS will pass9007199254740992to the function due to parsing precision loss before execution. Validating inputs insidesafeAddusingisSafeIntegerensures invalid runtime representations are flagged.