JavaScript Numbers, Math Object and BigInt: Rounding, Random and Precision

Prices, quantities, timeouts, percentages and IDs are all numbers, and tests compare them all the time. JavaScript numbers have a few surprises, such as 0.1 + 0.2 not being exactly 0.3, and IDs that silently lose digits. In this lesson you will learn how numbers are stored, how to round and format them correctly, how to use the Math object and random numbers for test data, and when to switch to BigInt.

Advertisement

📖 What You’ll Learn: the number type and floating-point precision, comparing decimals safely, integer limits, Infinity and NaN, number methods (toFixed, toPrecision, toLocaleString, Intl.NumberFormat), Number static methods, the Math object, random integers, money calculations in cents, and BigInt.


🔢 The Number Type

Definition: JavaScript has one number type for integers and decimals. Every number is stored as a 64-bit floating-point value (the IEEE 754 “double” format), the same as double in Java or float in Python.

📄 numbers.js

const quantity = 3;            // integer
const price = 19.99;           // decimal
const big = 1_000_000;         // _ separators make long numbers readable
const tiny = 2.5e-3;           // scientific notation: 0.0025
const hex = 0xff, binary = 0b1010, octal = 0o17;

console.log(quantity, price, big, tiny);
console.log(hex, binary, octal);
console.log(typeof quantity, typeof price);

⌨️ Terminal

node numbers.js

🖥️ Output

3 19.99 1000000 0.0025
255 10 15
number number

Numeric separators (1_000_000) are only for readability in source code; the value is the same as 1000000.


🎯 Floating-Point Precision: Why 0.1 + 0.2 !== 0.3

Many decimal fractions, such as 0.1, cannot be stored exactly in binary, just as 1/3 cannot be written exactly in decimal. Tiny rounding errors appear in the results:

📄 precision.js

console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log(19.99 * 3);
console.log(1.005 * 100);

⌨️ Terminal

node precision.js

🖥️ Output

0.30000000000000004
false
59.97
100.49999999999999

This is not a JavaScript bug; every language that uses IEEE 754 doubles behaves the same way. There are three safe ways to deal with it:

1. Compare with a tolerance

📄 tolerance.js

function almostEqual(a, b, tolerance = 1e-9) {
  return Math.abs(a - b) < tolerance;
}

console.log(almostEqual(0.1 + 0.2, 0.3));
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);

⌨️ Terminal

node tolerance.js

🖥️ Output

true
true

2. Round only for display

📄 display.js

const total = 19.99 * 3;
console.log(total.toFixed(2));          // "59.97" (a string)
console.log(Number(total.toFixed(2)));  // 59.97 (a number)

⌨️ Terminal

node display.js

🖥️ Output

59.97
59.97

3. Calculate money in whole cents (or paise)

📄 cents.js

const pricesInCents = [1999, 1999, 1999];
const totalCents = pricesInCents.reduce((sum, c) => sum + c, 0);
console.log(totalCents, "cents =", (totalCents / 100).toFixed(2));

⌨️ Terminal

node cents.js

🖥️ Output

5997 cents = 59.97

💡 Tip: Test frameworks have tolerance assertions built in. In Playwright and Jest use expect(total).toBeCloseTo(59.97, 2) instead of toBe for decimal results.


Advertisement

📏 Integer Limits, Infinity and NaN

A double can represent every integer exactly only up to 253 − 1. Beyond that, integers lose precision silently, which matters for large database IDs and timestamps in nanoseconds.

📄 limits.js

console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2); // precision lost!
console.log(Number.isSafeInteger(9007199254740993));
console.log(JSON.parse('{"orderId": 9007199254740993}').orderId); // last digit changed

⌨️ Terminal

node limits.js

🖥️ Output

9007199254740991
true
false
9007199254740992

📄 special.js

console.log(1 / 0, -1 / 0);          // Infinity, -Infinity
console.log(0 / 0, Math.sqrt(-1));   // NaN
console.log(Number.MAX_VALUE * 2);   // overflow -> Infinity
console.log(Number.isFinite(1 / 0), Number.isFinite(42));

⌨️ Terminal

node special.js

🖥️ Output

Infinity -Infinity
NaN NaN
Infinity
false true

⚠️ Watch out: Dividing by zero does not throw an error in JavaScript; it returns Infinity or NaN. Validate divisors (for example, an average over zero test runs) before calculating.


🛠️ Number Methods and Formatting

📄 methods.js

const n = 1234.5678;

console.log(n.toFixed(2));        // fixed decimals (string)
console.log(n.toFixed(0));        // rounds to a whole number
console.log(n.toPrecision(3));    // 3 significant digits
console.log((0.000123).toExponential(1));

console.log(Number.isInteger(5.0), Number.isInteger(5.5));
console.log(Number.parseFloat("2.5kg"), Number.parseInt("42", 10));

⌨️ Terminal

node methods.js

🖥️ Output

1234.57
1235
1.23e+3
1.2e-4
true false
2.5 42

toLocaleString() and Intl.NumberFormat format numbers the way people in a region expect, with grouping, currency symbols and percentages:

📄 format.js

const amount = 1234567.891;

console.log(amount.toLocaleString("en-US"));
console.log(amount.toLocaleString("en-IN"));   // Indian lakh/crore grouping
console.log(amount.toLocaleString("de-DE"));

const inr = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const pct = new Intl.NumberFormat("en-US", { style: "percent", maximumFractionDigits: 1 });
console.log(inr.format(1299.5), usd.format(1299.5), pct.format(0.875));

⌨️ Terminal

node format.js

🖥️ Output

1,234,567.891
12,34,567.891
1.234.567,891
₹1,299.50 $1,299.50 87.5%

💡 Tip: When a test checks a formatted price on a page, build the expected string with the same Intl.NumberFormat settings instead of hard-coding it. The test then stays correct for any amount.


🧮 The Math Object

Definition: Math is a built-in object with mathematical constants and functions. You never create it with new; call its methods directly.

📄 math.js

console.log(Math.round(4.5), Math.round(4.4), Math.round(-4.5));
console.log(Math.floor(4.9), Math.ceil(4.1), Math.trunc(-4.9));
console.log(Math.abs(-7), Math.sign(-7));
console.log(Math.max(3, 9, 4), Math.min(...[8, 2, 6]));
console.log(Math.pow(2, 10), 2 ** 10, Math.sqrt(144), Math.cbrt(27));
console.log(Math.PI.toFixed(4), Math.hypot(3, 4));

⌨️ Terminal

node math.js

🖥️ Output

5 4 -4
4 5 -4
7 -1
9 2
1024 1024 12 3
3.1416 5
MethodWhat it doesExample
Math.round(x)Nearest integer (.5 rounds up toward +∞)Math.round(2.5) → 3
Math.floor(x)Rounds downMath.floor(2.9) → 2
Math.ceil(x)Rounds upMath.ceil(2.1) → 3
Math.trunc(x)Removes the decimal partMath.trunc(-2.9) → -2
Math.max / minLargest / smallest argumentUse spread for arrays: Math.max(...arr)
Math.abs(x)Absolute valueMath.abs(-3) → 3
Math.random()Random number from 0 (inclusive) to 1 (exclusive)See below
Advertisement

Rounding to N decimal places

A common helper multiplies, rounds and divides. Because of floating-point errors, add Number.EPSILON for values like 1.005:

📄 round.js

const roundTo = (value, places) => {
  const factor = 10 ** places;
  return Math.round((value + Number.EPSILON) * factor) / factor;
};

console.log(Math.round(1.005 * 100) / 100); // naive version: 1 (wrong)
console.log(roundTo(1.005, 2));             // 1.01
console.log(roundTo(59.969999, 2));

⌨️ Terminal

node round.js

🖥️ Output

1
1.01
59.97

🎲 Random Numbers for Test Data

Math.random() returns a decimal from 0 up to (but not including) 1. Scale it to get random integers in a range:

📄 random.js

// Random integer from min to max, both included
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

const rolls = Array.from({ length: 10 }, () => randomInt(1, 6));
console.log("10 dice rolls:", rolls.join(" "));
console.log("all between 1 and 6?", rolls.every((r) => r >= 1 && r <= 6));

const items = ["pen", "book", "lamp"];
const pick = items[randomInt(0, items.length - 1)];
console.log("random item is valid?", items.includes(pick));

const email = `qa+${Date.now()}${randomInt(100, 999)}@sqatools.in`;
console.log("unique email format ok?", /^qa\+\d+@sqatools\.in$/.test(email));

⌨️ Terminal

node random.js

🖥️ Output

10 dice rolls: 2 5 6 4 2 2 3 5 2 1
all between 1 and 6? true
random item is valid? true
unique email format ok? true

The rolls change every run; the checks stay true. Unique emails built from Date.now() and a random part are a common way to avoid “user already exists” errors when tests create accounts.

⚠️ Watch out: Math.random() is not secure. For tokens or passwords use crypto.randomUUID() or crypto.getRandomValues(). And when a test fails with random data, log the data you used, or the failure cannot be reproduced.


🐘 BigInt: Integers of Any Size

Definition: bigint is a separate primitive type for whole numbers of any size. Create one with an n suffix or with BigInt().

📄 bigint.js

const id = 9007199254740993n;
const next = id + 1n;
console.log(id, next);
console.log(typeof id);
console.log(BigInt("123456789012345678901234567890") * 2n);
console.log(7n / 2n);                 // integer division: the decimal part is dropped
console.log(10n > 9, 10n == 10, 10n === 10);

⌨️ Terminal

node bigint.js

🖥️ Output

9007199254740993n 9007199254740994n
bigint
246913578024691357802469135780n
3n
true true false

You cannot mix BigInt and regular numbers in arithmetic; convert one of them explicitly:

📄 mix.js

const big = 10n;
console.log(big + 5);

⌨️ Terminal

node mix.js

🖥️ Output

/home/you/js-course/mix.js:2
console.log(big + 5);
                ^

TypeError: Cannot mix BigInt and other types, use explicit conversions
    at Object.<anonymous> (/home/you/js-course/mix.js:2:17)

Node.js v26.13.0

📄 mix-fixed.js

const big = 10n;
console.log(big + BigInt(5));
console.log(Number(big) + 5);

⌨️ Terminal

node mix-fixed.js

🖥️ Output

15n
15
  • BigInt has no decimals and does not work with Math methods.
  • JSON.stringify throws on BigInt values. Send large IDs as strings in APIs.
  • Use BigInt for large IDs, counters and cryptography; use regular numbers for everything else.

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. A cart has items priced 0.1 and 0.2. Write a check that confirms the total is 0.3 without failing because of floating-point errors.

Show answer

📄 practice1.js

const total = 0.1 + 0.2;
const ok = Math.abs(total - 0.3) < 1e-9;
console.log(total, ok ? "total is 0.3" : "total is wrong");

🖥️ Output

0.30000000000000004 total is 0.3

Q2. Calculate 18% GST on ₹1,499 and print the tax and the final price, both rounded to two decimal places.

Show answer

📄 practice2.js

const price = 1499;
const tax = Math.round(price * 0.18 * 100) / 100;
const finalPrice = Math.round((price + tax) * 100) / 100;
console.log(`Tax: ${tax.toFixed(2)}, Final: ${finalPrice.toFixed(2)}`);

🖥️ Output

Tax: 269.82, Final: 1768.82

Q3. Find the highest, lowest and average response time in [120, 340, 95, 210, 180] milliseconds. Print the average with no decimals.

Show answer

📄 practice3.js

const times = [120, 340, 95, 210, 180];
const max = Math.max(...times);
const min = Math.min(...times);
const avg = times.reduce((s, t) => s + t, 0) / times.length;
console.log(`max ${max} ms, min ${min} ms, avg ${Math.round(avg)} ms`);

🖥️ Output

max 340 ms, min 95 ms, avg 189 ms

Q4. Write randomPhone() that returns a 10-digit string starting with 9, and check that 5 generated numbers all match /^9\d{9}$/.

Show answer

📄 practice4.js

function randomPhone() {
  let digits = "9";
  for (let i = 0; i < 9; i++) {
    digits += Math.floor(Math.random() * 10);
  }
  return digits;
}

const phones = Array.from({ length: 5 }, randomPhone);
console.log(phones.every((p) => /^9\d{9}$/.test(p)));

🖥️ Output

true

Building the number digit by digit as a string keeps leading digits intact and avoids precision problems.

Q5. Format 2500000 as Indian rupees and as US dollars.

Show answer

📄 practice5.js

const amount = 2500000;
console.log(new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(amount));
console.log(new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount));

🖥️ Output

₹25,00,000.00
$2,500,000.00

Q6. An API returns the order ID "9007199254740995" as a string. Add 2 to it without losing precision and print the result as a string.

Show answer

📄 practice6.js

const id = "9007199254740995";
console.log(Number(id) + 2);              // precision lost
console.log((BigInt(id) + 2n).toString()); // exact

🖥️ Output

9007199254740998
9007199254740997

🧠 MCQ Quiz: Numbers, Math and BigInt

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does 0.1 + 0.2 === 0.3 return?
  2. How many number types does JavaScript have for integers and decimals (excluding BigInt)?
  3. What does (1.005).toFixed(2) return?
  4. What is Math.floor(-2.5)?
  5. Which expression returns a random integer from 1 to 6 inclusive?
  6. What is 1 / 0 in JavaScript?
  7. What is Number.MAX_SAFE_INTEGER?
  8. What happens with 10n + 5?
  9. How should a test compare a calculated decimal total?
  10. What does Math.max(...[4, 11, 7]) return?

💼 Interview Questions and Answers

Q1. Why is 0.1 + 0.2 not equal to 0.3, and how do you handle it?

Numbers are IEEE 754 binary doubles, and 0.1 and 0.2 have no exact binary representation, so their sum is 0.30000000000000004. Handle it by comparing with a tolerance (Math.abs(a - b) < 1e-9 or toBeCloseTo), rounding only when displaying (toFixed), or doing money arithmetic in integer cents, or with a decimal library for financial systems.

Q2. What is the difference between Math.round, Math.floor, Math.ceil and Math.trunc?

📄 rounding.js

for (const x of [2.5, -2.5, 2.4, -2.6]) {
  console.log(x, Math.round(x), Math.floor(x), Math.ceil(x), Math.trunc(x));
}

⌨️ Terminal

node rounding.js

🖥️ Output

2.5 3 2 3 2
-2.5 -2 -3 -2 -2
2.4 2 2 3 2
-2.6 -3 -3 -2 -2

round goes to the nearest integer, with .5 rounding toward positive infinity (so -2.5 becomes -2). floor always goes down, ceil always up, and trunc drops the fraction (toward zero).

Q3. A test intermittently fails when comparing order IDs from an API. The IDs are 19-digit numbers. What is wrong?

The IDs exceed Number.MAX_SAFE_INTEGER, so JSON.parse rounds them and different IDs can become equal or change their last digits. The API should send them as strings, and the test should compare them as strings or convert with BigInt. Check with Number.isSafeInteger().

Q4. How do you generate unique and reproducible test data?

For uniqueness, combine a timestamp, a random part or crypto.randomUUID(), for example qa+<timestamp>@domain. For reproducibility, log the generated values in the test report, or use a seeded random generator (for example Faker with faker.seed(123)) so a failing run can be repeated with the same data.

Q5. What is NaN, and how can it appear in a calculation?

NaN is a number value meaning “not a valid number”. It appears from failed conversions (Number("abc")), undefined maths (0 / 0, Math.sqrt(-1)), and arithmetic with undefined (a missing property). It spreads through every later calculation, so validate inputs with Number.isFinite() early.


Advertisement

❓ Frequently Asked Questions

🤔 How do I round a number to 2 decimal places in JavaScript?

For display, use num.toFixed(2) (returns a string). For a number, use Math.round((num + Number.EPSILON) * 100) / 100.

🤔 Does JavaScript have integers?

Regular numbers can hold integers exactly up to 253 − 1, but they are floating-point values. For larger integers use BigInt. Number.isInteger() tells you whether a number has no fractional part.

🤔 How do I generate a random number between two values?

Use Math.floor(Math.random() * (max - min + 1)) + min for an integer from min to max, both included.

🤔 When should I use BigInt?

Only for whole numbers larger than 9,007,199,254,740,991, such as large database IDs or nanosecond timestamps. It is slower and cannot be mixed with regular numbers.


🏁 Summary

  • All regular numbers are 64-bit floating-point values; 0.1 + 0.2 is not exactly 0.3.
  • Compare decimals with a tolerance, round only for display, and calculate money in cents.
  • Integers are exact only up to Number.MAX_SAFE_INTEGER; division by zero gives Infinity or NaN, not an error.
  • Math provides rounding, min/max, powers and random(); Intl.NumberFormat formats currencies and percentages.
  • BigInt (123n) handles integers of any size but cannot be mixed with regular numbers.

Next, continue with Lesson 10: Truthy, Falsy and Equality.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in