FSM Full Stack Masterclass
Platform under construction
JavaScript course badge

Strings, Numbers & Math

Intermediate

Precision & Random Values

Floating-point precision and random values are two places where JavaScript numbers need extra care.

0.1 + 0.2; // 0.30000000000000004

Math.floor(Math.random() * 10);
crypto.getRandomValues(new Uint32Array(1));

Strings, Numbers & Math

Precision and randomness are not details to guess about.

JavaScript numbers use binary floating-point. Many decimal fractions cannot be represented exactly, so tiny rounding errors can appear.

For display, rounding may be enough. For exact decimal domains, store integer units where possible or use a decimal library when accuracy requirements are strict.

Math.random is fine for simple visual randomness, sampling and small demos. It is not secure. For secure random values in the browser, use crypto.getRandomValues or crypto.randomUUID where appropriate.

Floating-point

Decimals can produce tiny precision differences.

Integer units

Store exact quantities as integers when possible.

Math.random

Useful for non-secure random UI behavior.

Crypto random

Use Web Crypto for security-sensitive randomness.

Examples

Start with the smallest working pattern.

Calculate exact decimal-like values as integers

const unitA = 10;
const unitB = 20;
const totalUnits = unitA + unitB;

console.log(totalUnits); // 30

Expecting decimal arithmetic to be exact

const total = 0.1 + 0.2;

console.log(total === 0.3); // false

Code patterns

Reusable examples for quick reference.

These small examples are designed for scanning. Use them when you need the syntax quickly, then read the surrounding notes when you want the deeper reason behind the pattern.

Round display output

Good for visible percentages and approximate values.

const value = 0.1 + 0.2;

console.log(value.toFixed(2)); // "0.30"

Use integer units

Avoid decimal drift by calculating in smaller whole units.

const centsA = 10;
const centsB = 20;
const totalCents = centsA + centsB;

console.log(totalCents); // 30

Random integer range

The common non-secure pattern for simple UI use.

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(randomInt(1, 6));

Secure random id

Use browser crypto for values that should not be predictable.

const id = crypto.randomUUID();

console.log(id);

Rules that matter

Keep text and numbers predictable.

Strings and numbers are simple until they cross a boundary: form input, API data, generated output, rounding, formatting or search. Normalize, validate and format deliberately.

Expect decimal drift

Tiny floating-point differences are normal for many decimals.

Round only for display

Rounding hides display noise but should not define core data rules by accident.

Use integer units for exact values

Whole-unit calculations are easier to keep exact.

Use Math.random only for non-secure randomness

It is not for tokens, passwords or security decisions.

Use crypto for secure randomness

Web Crypto provides stronger browser randomness.

Document range helpers

Random range functions should clearly define inclusive and exclusive bounds.

Production thinking

Small value mistakes become visible product mistakes.

Why does this matter?

Precision and randomness bugs can be hard to see. The code runs, but the number is slightly wrong or the random value is not safe enough.

Accessibility

Random UI behavior should not make interfaces unpredictable for keyboard users or assistive technology users.

Production note

Production code should separate approximate display math from exact business rules and use secure randomness for security-sensitive values.

SEO note

Random rendering should not change important content, headings or links in ways that make pages inconsistent for crawlers and users.

Live code lab

Change the HTML, CSS or JavaScript and run the result.

The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.

Mini assignment

Try this now.

  • Change the random range from 1-6 to 10-20.
  • Format the decimal result with toFixed(2).
  • Replace Math.random with crypto.randomUUID for an id example.

Practice assignment

Do this before moving to the next topic.

  1. Show why 0.1 + 0.2 is not exactly 0.3.
  2. Write a randomInt function with inclusive bounds.
  3. Write one example that calculates in integer units.

Try it yourself

Compare decimal and integer calculations

Live preview

Self-check

Before you continue, prove that you understand Precision & Random Values.

Intermediate

Explain the answer in plain language first. Then change the code example and verify that the result matches your explanation.

  1. Can you explain why 0.1 + 0.2 surprises people?
  2. Can you explain why integer units help exact calculations?
  3. Can you explain the bounds of Math.random?
  4. Can you explain why Math.random is not secure?
  5. Can you explain when crypto.randomUUID is useful?

Chapter checkpoint

Strings, Numbers & Math checkpoint

Finish this chapter by turning the lessons into a small practical proof.

Build

Build a small example that combines three lessons from this chapter.

Deliverables

  • working code
  • short explanation
  • self-check answers

Quality checks

  • readable code
  • clear failure path
  • accessibility considered

Review question

Can you explain the important tradeoff without reading from the page?