Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.4 — Math and Rounding
JavaScript · Example 2 of 3

toFixed, binary decimals and money in paise

toFixed rounds halves away from zero (-1.5 becomes -2) while Math.round rounds them up (-1). 1.005 is stored as slightly less than 1.005, so both ways give 1.00.

The built-in Math object gives you rounding (round, floor, ceil, trunc), min/max, powers, roots and random numbers. Rounding has rules that surprise people, toFixed returns a string, and money is safest stored as whole paise or cents.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write roundTo(x, places) that rounds a number to a given number of decimal places and returns a number (not a string), so roundTo(3.14159, 2) is 3.14.

02

Write toPaise(text) that turns a typed amount like "4.35" or "12" into whole paise (435, 1200).

03

Write percentOff(pricePaise, percent) that returns the discounted price in paise, rounded to the nearest paisa.

Explain it without notes

01

What is the difference between Math.floor and Math.trunc?

02

Why does (1.005).toFixed(2) give "1.00"?

03

How should an app store and add up prices?

04

How do you make a random integer between two values, and when is Math.random the wrong tool?

toFixed, binary decimals and money in paise

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

0.30000000000000004 0.30
10.00 string
1.00 1
-2 -1
1234.57 0.00012
434.99999999999994 434 435
[ 435, 10, 20, 9999 ] 10464
1884 123.48