Lesson 6: Mastering JavaScript Numbers, BigInt, and Precision, NAN and more with challenges!

π BigInt: Handling Large Integers
JavaScript's Number
type can safely represent integers up to 2^53 - 1
(Number.MAX_SAFE_INTEGER
). Beyond this, precision issues arise. Enter BigInt
, a numeric type that can represent integers of arbitrary size.β
Creating BigInts:
const big1 = 1234567890123456789012345678901234567890n; // Literal syntax
const big2 = BigInt("1234567890123456789012345678901234567890"); // Constructor
Key Characteristics:
- Arithmetic Operations: Use standard operators (
+
,-
,*
,/
,%
), but both operands must beBigInt
.β
10n + 20n; // 30n
5n / 2n; // 2n (truncates towards zero)
- Type Mixing: Cannot mix
BigInt
withNumber
directly.βMDN Web Docs+2DEV Community+2Stack Overflow+2
1n + 2; // TypeError
Conversions:
Number(bigIntValue)
may lead to precision loss if theBigInt
exceedsNumber.MAX_SAFE_INTEGER
.βBigInt(numberValue)
works ifnumberValue
is an integer.β
Serialization:
BigInt
cannot be serialized to JSON directly.βMDN Web Docs
JSON.stringify({ value: 10n }); // TypeError
// Workaround:
JSON.stringify({ value: 10n.toString() });
Limitations:
Cannot use
Math
methods withBigInt
.βNo support for decimal points.β
Unary plus (
+bigInt
) is not supported.β
π Object.is(): Precise Value Comparison
Object.is()
determines whether two values are the same value. It is similar to the strict equality operator (===
), but with some differences:βMDN Web Docs
Object.is(+0, -0)
returnsfalse
, whereas+0 === -0
istrue
.βObject.is(NaN, NaN)
returnstrue
, whereasNaN === NaN
isfalse
.β
Examples:
Object.is(NaN, NaN); // true
Object.is(+0, -0); // false
Object.is(0, -0); // false
Object.is(1, 1); // true
Object.is({}, {}); // false (different object references)
π’ Rounding and Precision
JavaScript uses IEEE 754 double-precision floating-point numbers, which can lead to precision issues:β
0.1 + 0.2 === 0.3; // false
Rounding Methods:
Math.round(x)
: Rounds to the nearest integer.βMDN Web Docs+1The Modern JavaScript Tutorial+1Math.floor(x)
: Rounds down to the nearest integer.βMDN Web Docs+21MDN Web Docs+21MDN Web Docs+21Math.ceil(x)
: Rounds up to the nearest integer.βMath.trunc(x)
: Removes the fractional part.βNumber.prototype.toFixed(digits)
: Rounds to a fixed number of decimal places and returns a string.βMDN Web Docs
javascriptCopyEdit (0.1 + 0.2).toFixed(2); // "0.30"
Workarounds for Precision Issues:
- Use
toFixed()
for rounding and then convert back to number:β
parseFloat((0.1 + 0.2).toFixed(10)) === 0.3; // true
- Use integer arithmetic when dealing with currency:β
// Represent $0.30 as 30 cents
10 + 20 === 30; // true
π§ͺ Type Checking Functions
isNaN()
vs. Number.isNaN()
:
isNaN(value)
: Converts the value to a number and checks if it'sNaN
.β
isNaN("abc"); // true
Number.isNaN(value)
: Checks if the value is strictlyNaN
without coercion.β
Number.isNaN("abc"); // false
Number.isNaN(NaN); // true
isFinite()
vs. Number.isFinite()
:
isFinite(value)
: Converts the value to a number and checks if it's finite.β
isFinite("10"); // true
Number.isFinite(value)
: Checks if the value is a number and finite without coercion.βMDN Web Docs
Number.isFinite("10"); // false
Number.isFinite(10); // true
πΉ 2. Fill Any Gaps β Advanced Insights, Internal Mechanics, and Pitfalls
β οΈ Common Pitfalls and Edge Cases
1. BigInt & Number Mixing = π¨ TypeError
console.log(1n + 1); // β TypeError: Cannot mix BigInt and other types
β Instead, explicitly convert:
console.log(1n + BigInt(1)); // 2n
console.log(Number(1n) + 1); // 2
2. BigInt in JSON = β Not Serializable
JSON.stringify({ value: 123n }); // β TypeError
β
Use .toString()
or a replacer:
JSON.stringify({ value: 123n.toString() }); // β
3. Floating-Point Arithmetic Precision
Due to IEEE 754, many devs mistakenly trust this:
0.1 + 0.2 === 0.3; // β false
β Use rounding:
Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON; // β
true
4. Object.is()
Differences
Object.is(+0, -0); // false β
+0 === -0; // true
Object.is(NaN, NaN); // true β
NaN === NaN; // false
β‘οΈ Use Object.is()
in polyfills or for corner-case comparisons.
5. toFixed()
Returns a String
typeof (1.2345).toFixed(2); // "string"
π§ Pro Tip: Wrap with parseFloat()
if you need a number.
6. Math.round()
& Banker's Rounding
JavaScript uses round half up, not bankerβs rounding:
Math.round(2.5); // 3
Math.round(-2.5); // -2
πΉ 3. Challenge Me Deeply β 10 Problems + 1 βAha!β Twister
π’ Basic
Check BigInt Limits
Write a function that checks if a number exceedsNumber.MAX_SAFE_INTEGER
and converts it toBigInt
safely.Object.is Checker
Implement a customisSameValue(x, y)
that mimicsObject.is()
using only basic operators.Round Me Right
Write a utility functionsmartRound(value, digits)
that rounds a number and returns a number (not string).
π‘ Intermediate
Currency Formatter
Build a function that takes a float (e.g., 19.899) and returns a formatted INR string likeβΉ19.90
, usingtoFixed()
.NaN Validator
Write a function that returns true only if input is actualNaN
, and false for anything else β without usingisNaN()
orNumber.isNaN()
.Safe Summation
Sum a list of prices like[0.1, 0.2, 0.3]
accurately. Avoid floating-point precision errors.BigInt Multiplication Table
Print the multiplication table of aBigInt
from 1n to 10n.
π΄ Advanced
BigInt Safe Parser
Write a function that parses very large integers from string input and performs math like addition/division safely.Dynamic Rounding Rules
Given an input with rounding rules (round up, floor, truncate), apply correct rounding method dynamically.Precision Loss Detector
Detect if a given number loses precision when converted from BigInt β Number.
π‘ Aha! Brain Twister
- Guess the Output
console.log(Object.is(NaN, NaN)); // ?
console.log(Object.is(+0, -0)); // ?
console.log((0.1 + 0.2).toFixed(2)); // ?
console.log(9007199254740991 + 1); // ?
console.log(9007199254740991 + 2); // ?
(Write down expected values, then verify!)
πΉ 4. Interview-Ready Questions
π Concept-Based
What is the difference between
Object.is()
,===
, and==
?How does
BigInt
differ fromNumber
internally and syntactically?Why does
(0.1 + 0.2) !== 0.3
in JavaScript?
π§© Scenario-Based
How would you ensure currency accuracy in an e-commerce app?
How would you store a user's Aadhaar number (12+ digit integer) safely in JavaScript?
π Debugging Style
A function returns
true
forisNaN("Hello")
β whatβs wrong?Why does your API return
"100.00"
instead of a number?
β Best Practices
π Do:
Use
BigInt
for large integer-only domains (cryptography, finance).Use
toFixed()
+parseFloat()
for user-facing rounded numbers.Use
Object.is()
for edge-case comparisons.
π« Avoid:
Mixing
BigInt
withNumber
without conversion.Trusting
==
or===
to compareNaN
.Assuming JSON can serialize
BigInt
.
πΉ 5. Real-World Usage
π¦ Front-End
Currency formatting (
toFixed
, rounding).UI display of prices, ratings, or scores.
Displaying long IDs or account numbers using
BigInt
.
π Back-End (Node.js)
Dealing with cryptographic values, blockchain transaction IDs (BigInt).
Big financial data β no floating point allowed.
π οΈ Frameworks/Libraries
Lodash: has utilities for precision-safe rounding.
BN.js / Big.js: used for BigInt support before native
BigInt
arrived.Intl.NumberFormat: modern API for formatting numbers/currencies.
πΉ 6. Remember Like a Pro
π§ Mnemonics & Visuals
Object.is()
is like === on steroids: remembersNaN β NaN
and+0 β -0
.BigInt
= Big Integer (No fractions, no decimal).isNaN
is loose,Number.isNaN
is strict.
π§Ύ Cheatsheet
Comparison | == | === | Object.is() |
NaN | false | false | β true |
+0 vs -0 | true | true | β false |
1 vs 1 | true | true | β true |
{} vs {} | false | false | β false |
Rounding Function | Effect |
Math.round(x) | Nearest integer |
Math.floor(x) | Rounds down |
Math.ceil(x) | Rounds up |
Math.trunc(x) | Removes decimals |
x.toFixed(n) | Rounds and fixes decimals |
πΉ 7. Apply It in a Fun Way β Mini Project Idea
π‘ Currency Calculator (INR)
Goal: Build a utility to sum item prices like βΉ99.99 + βΉ10.25 + βΉ15.50 and return a properly formatted total with accurate rounding.
π Steps:
Accept a list of prices as floats.
Convert all to cents (integers):
βΉ99.99 β 9999
.Sum in integers.
Convert back to float with
.toFixed(2)
.Format the output as
βΉXXX.XX
.
β Bonus Extensions:
Support
BigInt
mode for super-high value transactions.Add currency switcher (
INR
,USD
,EUR
) usingIntl.NumberFormat
.
π§ (Optional) Extra Value
π§© Open Source Usage:
Ethereum/Web3 DApps: Use
BigInt
for large balances.Finance Libraries: Use
toFixed
,BigInt
,Math
for accurate rounding.Crypto APIs: Use
BN.js
,bignumber.js
.
β οΈ Common Dev Mistakes
Using
===
to compareNaN
.Assuming
+0 === -0
implies they're the same value.Forgetting
toFixed()
returns a string.Using
JSON.stringify()
directly on BigInt.
β‘ Performance Tips
Avoid excessive type conversions (BigInt <-> Number).
Round early when working with floats to reduce propagation error.
Subscribe to my newsletter
Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
