Turn typed text into a number with Number() and catch NaN with Number.isNaN(), because NaN spreads and never equals itself. See why 1.1 + 2.2 prints 3.3000000000000003, round on purpose with Math.round, floor, ceil and toFixed, read TS2845, and make TaskKit say how full today’s list is.
TypeScript
Fundamentals
Number pitfalls: NaN, floating point, and Math. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
The shopping list on the fridge has grown a column. Next to each
item, whoever bought it last wrote what it cost: milk 1.10, bread
2.20. Ana wants the total, so she writes three lines of
TypeScript: one box for each price and a line that adds them.
She expects 3.3. The program prints 3.3000000000000003.
Nothing is broken, and the program is not lying. Numbers have their
surprises, just as strings had theirs in capitals and positions, and
this one comes from how a computer keeps a decimal in a box. A
second surprise comes from text: a time estimate typed as "ten"
turns into a value that is a number and still prints NaN, "not a
number". By the end of this lesson you will turn text into a number
and check that it worked, know why some decimals come out a hair
off, round them on purpose with Math, and TaskKit will say how
full today's list is, in whole percent.
Text that should be a number
In lesson 2.2 you saw that quotes make text: "15" is a string,
even though every character in it is a digit. Text is what you get
whenever a person types something. In the last lesson of this module
TaskKit starts reading what you type after its name in the terminal,
and every word of it arrives as a string. A time estimate typed as
15 arrives as "15", and "15" + 5 glues instead of adding, as
lesson 2.3 showed.
So before you count with typed text, you turn it into a number.
Number is the command lesson 2.2 promised (as a type, a number box
is still : number, in lower case): put the text in its brackets,
and it gives back the number the text spells:
It prints 20, 20, 6.5 and 5. Spaces at the ends are
ignored, as if Number called trim() first, and a decimal
point is read as a decimal point. The last line is the odd one:
an empty string becomes 0, not an error. Remember it for the day
somebody presses Enter without typing anything.
NaN: the number that is not a number
Number can only give back a number, so what does it do with text
that spells none, such as "ten"? It gives back NaN, short
for not a number. You met it once in Module 1, when "=" * 28
printed NaN instead of a line. NaN is a special value of the
type number that means "this calculation had no answer". It is not
an error: nothing stops, and nothing names the line.
And it spreads. Any arithmetic with NaN on one side gives NaN,
so one bad value turns every box worked out from it into NaN
too. Press Next step to watch it travel:
CodeThe program, line by line. The marked line is the one the computer is running now; the lines above it have run.ts
ts
const text = "ten";const minutes = Number(text);const total = minutes + 15;console.log("Total:", total);
MemoryThe boxes in memory, each with its name. A box appears when a line makes it; the one just filled or changed is orange.
text"ten""ten"
minutesNaNNaN
totalNaNNaN
OutputEverything the program has printed so far.
Nothing printed yetNothing printed yet
Every step as text
Line 1.text = "ten".
A person typed the estimate as a word. The box holds the text
"ten".
Line 2.text = "ten", minutes = NaN.
Number() cannot read "ten" as a number, so it gives back
NaN. No error: the program carries on.
Line 3.text = "ten", minutes = NaN, total = NaN.
NaN plus 15 is NaN. Every sum with NaN in it gives NaN.
Line 4.text = "ten", minutes = NaN, total = NaN.
The line prints Total: NaN, three lines away from the word that
caused it.
Prints Total: NaN
NaN goes into one box, and every box worked out from it
TypeScript does not object to any of it. Rest the pointer on
minutes (hover over it) in VS Code (Visual Studio Code, your
editor), and it says const minutes: number, which is true: NaN
is a number value, so the box fits. TypeScript checks the kind of
value a box holds. Whether "ten" turns into a useful number is
only known when the program runs.
So the program has to ask. The obvious question, === NaN, does
not work: NaN is the one value that is not equal to anything,
itself included. Ask with Number.isNaN() instead. Like
console.log, it is a method that belongs to a name, here
Number, and it gives back a boolean:
It prints true, then false: the typed text was not a number, and
"15" was. Asking with === is not just unhelpful but refused:
TypeScript knows NaN === NaN can only be false, and the common
mistake at the end of this lesson shows what it says. In Module 3
the answer of Number.isNaN() decides what happens next: a program
refuses an estimate it cannot read.
Why 1.1 + 2.2 is not 3.3
Write one third as a decimal: 0.333…, and the threes never end.
However many you write, you stop somewhere, and what you wrote is a
hair less than one third. Decimal digits, which count in tens, can
never write a third exactly.
A computer has the same problem with different numbers. It does not
count in tens, but in halves: a half, a quarter, an eighth, and so
on. So 0.5 and 0.25 fit exactly, and one tenth, 0.1, is for a
computer what one third is for us: written in halves, it never ends.
A box gets a fixed amount of room for each number, so a decimal like
1.1 is kept as the nearest number the room allows. This way of
keeping decimals is called floating point, and every number box
in TypeScript uses it.
Most of the time you never see the difference: printing rounds it
away, so console.log(1.1) prints 1.1. You see it when two
such numbers are added and their small errors land together.
Press Next step to follow it, or let it play:
1.1 is kept as 1.1000000000000001
A hair above 1.1: the nearest number the box can hold.
Printed, it still shows as 1.1.
2.2 is kept as 2.2000000000000002
A hair above 2.2, for the same reason. Printed, it still
shows as 2.2.
1.1 + 2.2 gives 3.3000000000000003
The two hairs add up, and the sum lands on the next number up:
too far from 3.3 to print as 3.3.
3.3 is kept as 3.2999999999999998
3.3 itself sits a hair below. Two neighbours, so
1.1 + 2.2 === 3.3 is false.
Each decimal is kept as the nearest number a box can hold
All 4 steps shown.Step 1 of 4: 1.1 is kept as 1.1000000000000001Step 2 of 4: 2.2 is kept as 2.2000000000000002Step 3 of 4: 1.1 + 2.2 gives 3.3000000000000003Step 4 of 4: 3.3 is kept as 3.2999999999999998
All 4 steps shown.
The sum and 3.3 end up as two neighbouring numbers, one on each side
of 3.3. Run it. The third line is the best-known example of the same
hair; the last two are sums whose numbers a box holds exactly:
It prints 3.3000000000000003, false, 0.30000000000000004,
0.75 and 330. Halves and quarters are kept exactly, and so are
whole numbers, up to far more than you will ever count. The trouble
is only with decimals such as tenths and hundredths, which is to say
with prices.
This is not a TypeScript bug, and switching languages will not
fix it: Python, Java and your spreadsheet keep numbers the same
way, and a spreadsheet hides it by rounding what it shows. That
is the fix here too. Round on purpose, when you show a number and
when you compare one.
Math: rounding on purpose
Math is a name that comes with the language, the way console
does, and its methods do arithmetic that the operators cannot. Three
of them make a whole number out of a decimal, and each treats the
part after the point its own way:
index.ts
Math.round(2.5)// 3Math.round(2.4)// 2
Math.round
Does: Goes to the nearest whole number; .5 goes up
Never: It never keeps a single decimal place
index.ts
Math.floor(2.5)// 2Math.floor(2.9)// 2
Math.floor
Does: Always goes down to the whole number below
Never: 2.9 never becomes 3
index.ts
Math.ceil(2.5)// 3Math.ceil(2.1)// 3
Math.ceil
Does: Always goes up to the whole number above
Never: 2.1 never stays 2
Three ways to turn a decimal into a whole number
floor is the floor under you and ceil, short for ceiling, the
ceiling above: pick by what the number means. A task that takes 2.1
hours needs 3 hours set aside, so that is Math.ceil. Like string
methods, none of them changes the box it reads; each gives back a
new number.
Math.round only makes whole numbers, but a price needs two
decimal places. The trick is to round in cents: multiply by 100,
round, and divide by 100 again. The hair is gone, and === works:
The first prints Total: 3.3000000000000003 on a receipt somebody
reads; the second prints Total: 3.30. Notice that toFixed()
gives back a string, "3.30", not a number: that is how it can keep
the 0 at the end, which a number would drop. It is for showing,
never for counting. Add 1 to it and + glues, as in lesson 2.3:
(1.1 + 2.2).toFixed(2) + 1 is "3.301".
TaskKit shows how full the list is
TaskKit already says how many tasks it added and how much room
is left. A percentage reads faster: added / limit, times 100.
With a limit of 5 it comes out whole, but a limit of 3 would give
66.66666666666666, so round it. Open index.ts in
~/projects/taskkit and add the two lines marked + at the end:
index.tsts
const version = "0.1";const line = "=".repeat(28);console.log(line);console.log("TaskKit", version);console.log("Your tasks, in your terminal");console.log(line);const limit = 5;let added: number = 0;const tidyFirst = " buy milk ".trim();const firstTask = tidyFirst.slice(0, 1).toUpperCase() + tidyFirst.slice(1);console.log("Added:", firstTask);added = added + 1;const tidySecond = "call the dentist ".trim();const secondTask = tidySecond.slice(0, 1).toUpperCase() + tidySecond.slice(1);console.log("Added:", secondTask);added = added + 1;const room = limit - added;console.log( `Tasks added: ${added} of ${limit}, room for ${room} more`);const percent = Math.round((added / limit) * 100);console.log(`List ${percent}% full`);
The parentheses show the order plainly: divide first, as you would
on paper. Check the file with tsc (short for TypeScript
compiler), which npx starts, then run it:
bash
npx tsc --noEmit index.tsnode index.ts
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Buy milkAdded: Call the dentistTasks added: 2 of 5, room for 3 moreList 40% full
Change limit to 3 and run it again: the last line says
List 67% full, a whole number. Without Math.round it would
say List 66.66666666666666% full. Put the 5 back when you are
done.
Predict before you run
Number reads the whole text or nothing. Decide what this
prints before you run it.
You read an estimate and want to see whether it was a number.
Everywhere else you ask whether two values are the same with
===, so you ask the same way here. VS Code draws a wavy line
under the question:
ts
const text = "ten";const minutes = Number(text);console.log(minutes === NaN);
This condition will always return 'false'.
Common mistake
Asking whether a value is NaN with ===
npx tsc --noEmit index.ts refuses line 3 with TS2845, before
anything runs:
index.tsts
const text = "ten";const minutes = Number(text);console.log(minutes === NaN);
NaN is never equal to anything, not even to NaN, so the
question can only ever answer false. TypeScript knows that and
says so. Under the message it adds a second line with a guess,
the way Did you mean did in Module 1:
Did you mean 'Number.isNaN(minutes)'?. Here the guess is the
fix.
This condition will always return 'false'.
The fix
Ask Number.isNaN(), which answers true for NaN:
index.tsts
const text = "ten";const minutes = Number(text);console.log(Number.isNaN(minutes));
Run the broken file with node alone and nothing checks it: it
prints false, as if "ten" were a fine number, and no message
appears. When a check for NaN seems never to fire, look for
=== NaN and replace it with Number.isNaN().
This program should print Total: 0.80, but it prints
Total: 0.7999999999999999, a hair below. Fix the last line so it
prints the total with exactly two decimal places.
Loading the editor…
Exercise · Fix the error
Catch the estimate nobody can read
This program should print Bad input: true, because "15 min"
is not a number. TypeScript refuses it. Fix the last line.
Loading the editor…
Exercise · Write the code
Split the bill to the cent
Three people share a bill of 10. Make a box share with each
person's part as a number rounded to cents, and print this line
with a template string:
text
Each pays 3.33
Loading the editor…
Recap
Recap · 3 questions
Check yourself
What type does TypeScript give Number("ten")?
Check yourself
Why does 1.1 + 2.2 print 3.3000000000000003?
Check yourself
What does (1.1 + 2.2).toFixed(2) give?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Number pitfalls: NaN, floating point, and Math
What things are
Word
What it means
NaN
Not a number: a number value with no answer in it
Infinity
What a number above 0 divided by 0 gives
Floating point
How a box keeps a decimal: as the nearest it can
Math
A name that comes with the language, full of arithmetic
Code
Write
To
Number("15")
Turn text into a number: 15
Number.isNaN(minutes)
Ask whether a value is NaN
Math.round(2.5)
Go to the nearest whole number: 3
Math.floor(2.9)
Go down to a whole number: 2
Math.ceil(2.1)
Go up to a whole number: 3
Math.round(x * 100) / 100
Round a number x to two decimal places
total.toFixed(2)
Show two decimal places, as a string
Rules
Rule
What it means
Whole text
Number("15 min") is NaN; Number("") is 0
NaN spreads
Every sum with NaN in it gives NaN
Never === NaN
NaN equals nothing; ask Number.isNaN()
A hair off
Tenths and hundredths are kept nearly, not exactly
Round first
Round before you show or compare a decimal
toFixed is text
For showing only: + 1 glues instead of adding
TS2845
The condition always gives the same answer: often === NaN
: number
The type stays lower case; Number() is a command
Where to go next
You can now turn typed text into a number and check whether it
worked, recognise NaN and stop it before it spreads, explain why
1.1 + 2.2 prints a hair too much, and round on purpose with
Math.round, Math.floor, Math.ceil and toFixed. TaskKit
says how full today's list is, in whole percent.
Next is Inference: when TypeScript knows the type and when to
write it yourself. You rested the pointer on minutes and
TypeScript already knew it was a number without being told. The
next lesson explains how it works that out, and when writing the
type yourself is still worth it.
Before you move on, work out a time estimate in a file of its own.
In ~/projects/taskkit, make hours.ts with a box estimate that
holds Number("25"), the minutes the tasks will take, and print
Hours needed: 1: estimate / 60 rounded up to a whole hour with
Math.ceil. Check it with npx tsc --noEmit hours.ts and run it
with node hours.ts. Then change "25" to "twenty", run it
again, and read what it prints. Delete hours.ts when you are done:
it is not part of TaskKit.