JavaScript Foundations·The beginner gaps

Dates and numbers

Work with dates and money safely, and avoid floating point surprises.

Beginner 13 min read Lesson 7 of 480 Challenge included
What you will be able to do
  • Create dates and read their parts
  • Compare moments using timestamps
  • Format numbers and currency with Intl.NumberFormat
  • Avoid floating point surprises when handling money

In plain English

A Date object represents a moment in time, and its timestamp is the number of milliseconds since 1 January 1970, which is how computers compare and sort dates. You create a date with new Date() and read its parts, like the year or month. Intl.NumberFormat formats numbers for a locale by adding commas, currency symbols and the right number of decimals. JavaScript numbers use floating point, so decimals like 0.1 cannot be stored exactly, which is why 0.1 + 0.2 is not quite 0.3; round money at the end with toFixed or work in whole cents.

Step by step

  1. 1Create a Date and read its year and month.
  2. 2Subtract two dates to get the difference in milliseconds, then convert to days.
  3. 3Format a number as currency with Intl.NumberFormat.
  4. 4Check that 0.1 + 0.2 is not exactly 0.3, then round it with toFixed.
dates.jsJavaScript
const now = new Date();
console.log(now.getFullYear());

const start = new Date("2024-01-01");
const end = new Date("2024-01-08");
const diffMs = end - start;
const diffDays = diffMs / (1000 * 60 * 60 * 24);
console.log(diffDays);

const money = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD"
});
console.log(money.format(1234.5));

console.log(0.1 + 0.2);
const price = (0.1 + 0.2).toFixed(2);
console.log(price);

Common mistakes

  • Using getMonth() and forgetting it is zero-based, so January is 0.
  • Expecting 0.1 + 0.2 to equal exactly 0.3 in JavaScript.
  • Comparing dates as strings instead of using their timestamps.
  • Rounding money with Math.round on a decimal instead of working in whole cents.
Your turn

Safe money total

Medium

Write a function totalCents(prices) that takes an array of dollar amounts and returns the total in whole cents, avoiding floating point errors.

JAVASCRIPT · starter
function totalCents(prices) {
}
Check your understanding before moving on.
Knowledge checkQuestion 1

What is the value of 0.1 + 0.2 in JavaScript?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 7 of 480 · 0% of course