Decimal

Term side of the Card.
Topic: Number Systems
Unit title: Decimal
Categories: Concept, Format
Explanation side of the Card

Explanation: The base-10 number system, which uses ten digits (0 to 9). It's the most familiar system to humans for counting and arithmetic.

Example

Wrongjs
const total = 0.1 + 0.2;
console.log(total === 0.3); // false
Rightjs
const totalCents = 10 + 20;
console.log(totalCents === 30); // true

Binary floats can't store most decimal fractions exactly, so money is kept in integer cents.

Common mistakes

  • Storing prices as floats and getting totals like 0.30000000000000004.

Key points

  • Money is stored as integer minor units, like cents, or a decimal type, not binary floats.
  • Floats are compared with a tolerance like Number.EPSILON, not ===.
  • Money columns in SQL use DECIMAL or NUMERIC, not FLOAT.

Interview questions

Why can't computers store 0.1 exactly?

Numbers are stored in binary, and 0.1 has an infinite binary fraction, so it is rounded to the closest value that fits.

Should I use toFixed to fix float errors?

Only for display. toFixed returns a rounded string; do the math in integers or a decimal library.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy