BBizKit

equal.numeric

v0.1.0 latest

Numeric equality per ECMA-262 Number coercion, rejecting hex/binary/octal notation for safety.

equalitynumericcomparisontype-coercionvalidation

Numeric equality per ECMA-262 Number coercion, rejecting hex/binary/octal notation for safety.

Signature

function numeric(a: string | number, b: string | number): boolean

Problem

Comparing numeric values from different sources (form inputs as strings, API responses as numbers) requires safe type coercion. parseFloat/Number have pitfalls: NaN propagation, hex acceptance, empty-string-to-zero coercion.

How It Works

Compares two values as numbers, coercing strings via Number(). Rejects non-decimal notations (hex 0x, binary 0b, octal 0o), NaN, Infinity, and empty strings with TypeError.

Boundaries

  • NaN, Infinity, -Infinity → TypeError (not finite).
  • Empty or whitespace-only strings → TypeError.
  • null, undefined, boolean → TypeError (must be string or number).
  • Hex/binary/octal notation (e.g. '0xFF') → TypeError.
  • Leading/trailing whitespace in strings is trimmed before conversion.

Replaces

Common boilerplate this function replaces:

parseFloat(a) === parseFloat(b) // but with proper NaN/Infinity/hex guards

Examples

equal.numeric("1.0", 1);  // true
equal.numeric("  42  ", 42);  // true
equal.numeric("1e2", 100);  // true
equal.numeric("0xFF", 255);  // TypeError
equal.numeric("", 0);  // TypeError

Standards

Caveats

  • Hex notation (0xFF) is rejected to prevent accidental semantic mismatches between numeric bases.
  • Scientific notation (1e2) is accepted as it is standard decimal notation.

FAQ

How to safely compare a string number and a number in JavaScript?

equal.numeric('42', 42) returns true. Handles whitespace, scientific notation, and rejects unsafe inputs.

Why does equal.numeric reject hex notation?

To prevent accidental semantic mismatches. '0xFF' (hex 255) and 255 (decimal) have different semantic meanings in many contexts.

Does equal.numeric handle NaN?

It throws TypeError for NaN. NaN is not a valid numeric comparison operand.

Can I compare boolean values with equal.numeric?

No. Booleans throw TypeError. Use equal.bool for boolean comparison.

Does equal.numeric trim whitespace?

Yes. equal.numeric(' 42 ', 42) returns true.