JavaScript lesson · 16 min
JavaScript Numbers and Math
Use numbers for totals, percentages, rounding, and practical calculations.
What you will practice
- Calculate totals and percentages.
- Round values with Math.round.
- Format numbers for readable output.
What this means
JavaScript has one main number type for everyday numeric work. You use it for prices, counts, percentages, sizes, coordinates, timers, and chart values.
Arithmetic operators such as `+`, `-`, `*`, and `/` work the way you expect, but real applications usually also need rounding and formatting.
`Math` is a built-in object with helpers like `Math.round`, `Math.floor`, `Math.ceil`, `Math.min`, and `Math.max`.
If this is your first time seeing this
Numbers power calculations: totals, counts, scores, dimensions, time differences, and percentages.
Whenever a result will be read by a human, think about rounding and units.
Mini glossary
- Number
- JavaScript's main type for numeric values.
- Math.round
- Rounds a number to the nearest integer.
- Operator
- A symbol such as `+`, `-`, `*`, or `/` that performs an operation.
Example from everyday life
Numbers in code are like a receipt. You add line items, subtract discounts, calculate tax, and round the final amount so a person can actually read and pay it.
How it works step by step
- The code starts with a price, quantity, and discount.
- It calculates the subtotal by multiplying price by quantity.
- It subtracts the discount and calculates tax from the discounted value.
- `Math.round(value * 100) / 100` rounds the final number to two decimal places.
Where you will use this
- A shopping cart calculates totals, discounts, tax, and delivery costs.
- An analytics dashboard turns raw counts into percentages.
- An image tool calculates target dimensions and compression ratios.
Before you run the code
Most number bugs come from unclear units or missing rounding. Be explicit about whether a value is dollars, cents, pixels, seconds, or percent.
For serious money systems, store amounts in cents or use a decimal library. For learning and UI estimates, normal JavaScript numbers are enough.
Common beginner mistakes
- Displaying too many decimal places.
- Mixing units, such as cents and dollars or seconds and milliseconds.
- Using normal floating-point numbers for serious accounting without extra care.
Run the code to see console output here.
Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.
Try changing this next
- Change the quantity and predict the new total.
- Change the tax rate to `0.2`.
- Use `Math.ceil` instead of `Math.round` and compare the result.