Data Types Explained: Integers, Floats, Booleans and Why They Differ

data types

Every beginner hits the same wall sooner or later. They add 0.1 and 0.2, get 0.30000000000000004, and decide the computer is broken. It is not broken. It is doing exactly what you told it to do, and what you told it depends on a choice you probably made without noticing: the data type. This guide explains integers, floats and booleans from the ground up, shows why the computer treats them so differently, and walks through the real bugs that happen when you pick the wrong one.

Why computers need types at all

A computer’s memory is a very long row of tiny switches, each either off or on. That is all it holds: zeros and ones. There is no such thing as a “number” or a “letter” down there. The pattern 01000001, for example, can mean the whole number 65, or it can mean the capital letter A, or it can be one tiny piece of a colour in a photograph. The bits themselves do not say which.

The data type is the label that tells the computer how to read a pattern. It answers three questions at once: how many switches does this value use, how should those switches be interpreted, and which operations make sense on it. You can add two numbers, but adding two pieces of text sticks them together instead, and asking whether a yes/no answer is “greater than 7” makes no sense at all.

Think of a kitchen. A measuring jug, a kitchen scale and a thermometer all give you a number, but you would not use the thermometer to weigh flour. Each tool suits a kind of question. Data types are the same: tools for different kinds of facts.

Integer42whole numbers,for countingFloat3.14has a decimal point,for measuringBooleanTrueyes or no,for decidingString’42’text in quotes,for labels
The four types you will meet in almost every language. Three of them are numbers or number-like; one is text.

The short version. An integer is a whole number, exact and used for counting. A float is a number with a decimal point, built for measuring and only approximately exact. A boolean is a yes/no value, either true or false. They differ because each is stored in a different way, and the way it is stored decides what it can do well and where it quietly goes wrong.

Integers: whole numbers, exact answers

An integer is a number with no fractional part: −3, 0, 7, 52,314. It is the type for anything you count. The number of people in a stadium, the number of items in a shopping cart, a person’s age in years, the page you are on: all integers. You cannot have 2.5 people in the stadium, so the type simply has no room for a fraction.

The big strength of integers is that they are exact. If you add 3 and 4, you get precisely 7, every time, forever. There is no rounding and no hidden error. That reliability is why money, counters, loops and array positions all lean on integers.

How an integer is stored

Computers store integers in binary, using a fixed number of bits. With 8 bits you have 256 possible patterns. If all of them are used for non-negative numbers (an “unsigned” integer), the range is 0 to 255. That is exactly why colour values on a screen run from 0 to 255: each of red, green and blue gets one byte.

If you also want negative numbers (a “signed” integer), one bit effectively goes to the sign, and the same 256 patterns cover −128 to 127. Wider integers get far more room: 16 bits cover −32,768 to 32,767, 32 bits cover about −2.1 billion to 2.1 billion, and 64 bits cover roughly −9.2 quintillion to 9.2 quintillion.

Overflow: when the number does not fit

Here is where integers can bite. A fixed-width integer has a biggest value, and adding one more does not produce an error in many languages. It wraps around, like a car odometer rolling from 99999 back to 00000.

Biggest 8-bit value127Add 1+ 1Wraps around−128In binary, 01111111 plus one is 10000000, which a signed integer reads as −128.
A signed 8-bit integer at its maximum. One more step and it flips to the most negative value.

I ran the numbers to be sure I was not just repeating folklore. This short program simulates what a signed integer of each width does when you add one to its maximum, and also shows the famous Unix time limit.

import struct
from datetime import datetime, timezone

def wrap(value, bits):
    """What a signed integer of this width does when it overflows."""
    m = 1 << bits
    v = value % m
    return v - m if v >= m // 2 else v

for bits in (8, 16, 32):
    top = 2 ** (bits - 1) - 1
    print(f"{bits:>2}-bit signed: max {top:>11,}   max + 1 wraps to {wrap(top + 1, bits):>14,}")

print()
last = 2 ** 31 - 1
print("32-bit Unix time limit:", datetime.fromtimestamp(last, tz=timezone.utc))
print("one second later wraps to:", datetime.fromtimestamp(wrap(last + 1, 32), tz=timezone.utc))

print()
print("Python int keeps going: 2**63 =", 2 ** 63)
print("float loses whole numbers:", float(2 ** 53) + 1 == float(2 ** 53))
print()
for code, name in (("b", "tiny int"), ("h", "short int"), ("i", "int"), ("q", "long int"), ("f", "float32"), ("d", "float64"), ("?", "boolean")):
    print(f"{name:<10} {struct.calcsize(code)} byte(s)")

Output:

 8-bit signed: max         127   max + 1 wraps to           -128
16-bit signed: max      32,767   max + 1 wraps to        -32,768
32-bit signed: max 2,147,483,647   max + 1 wraps to -2,147,483,648

32-bit Unix time limit: 2038-01-19 03:14:07+00:00
one second later wraps to: 1901-12-13 20:45:52+00:00

Python int keeps going: 2**63 = 9223372036854775808
float loses whole numbers: True

tiny int   1 byte(s)
short int  2 byte(s)
int        4 byte(s)
long int   8 byte(s)
float32    4 byte(s)
float64    8 byte(s)
boolean    1 byte(s)

Look at the date line. Many systems count time as the number of seconds since 1 January 1970, stored in a signed 32-bit integer. That counter runs out at 03:14:07 UTC on 19 January 2038. One second later it wraps to a large negative number, which a computer reads as December 1901. This is the “Year 2038 problem”, and engineers have been moving systems to 64-bit time to avoid it.

Real overflow stories

Overflow is not only a classroom curiosity. In 1996 the first launch of Europe’s Ariane 5 rocket ended in self-destruction after a value converted from a 64-bit floating-point number into a 16-bit signed integer was too large to fit. In December 2014, the view counter for the video “Gangnam Style” passed 2,147,483,647, the top of a 32-bit signed integer, and YouTube said it had to switch the counter to 64 bits. Both are reminders that the width of an integer is a decision, not a detail.

Python has an unusual comfort here: its integers grow as large as memory allows, so 2100 is simply 1,267,650,600,228,229,401,496,703,205,376. Languages such as C, Java and Go use fixed widths, and there you must choose carefully.

Floats: numbers with a decimal point

A float, short for floating-point number, is for values that can have a fractional part: 3.14, 36.6, 0.0001, 6.02 × 1023. Use it for things you measure rather than count: body temperature, the length of a table, the speed of a car, the voltage across a battery.

The name “floating point” describes how the number is stored. Instead of fixing the decimal point in one place, the computer keeps two pieces: the significant digits, and an exponent that says where the point floats to. It is the same idea as scientific notation. The number 6,020,000 can be written 6.02 × 106: the digits 6.02 and the exponent 6. A float stores a pair like that, but in binary.

This design gives floats a huge range. A standard 64-bit float, which most languages call a “double”, reaches from about 2.2 × 10−308 up to about 1.8 × 10308. No integer of the same size comes close. The price is exactness.

The 0.1 + 0.2 mystery, solved

Let me show you the thing that confuses everyone, then explain it. In Python:

import math

print("7           ->", type(7).__name__)
print("7.0         ->", type(7.0).__name__)
print("True        ->", type(True).__name__)
print('"7"         ->', type("7").__name__)
print()
print('"5" + "5"           =', repr("5" + "5"))
print('5 + 5               =', 5 + 5)
print('int("5") + int("5") =', int("5") + int("5"))
print()
print("10 / 4  =", 10 / 4)
print("10 // 4 =", 10 // 4)
print("10 % 4  =", 10 % 4)
print()
print("True + True       =", True + True)
print("isinstance(True, int) =", isinstance(True, int))
print("0.1 + 0.2         =", 0.1 + 0.2)
print("0.1 + 0.2 == 0.3  =", 0.1 + 0.2 == 0.3)
print("isclose           =", math.isclose(0.1 + 0.2, 0.3))
print("2 ** 100          =", 2 ** 100)

Output:

7           -> int
7.0         -> float
True        -> bool
"7"         -> str

"5" + "5"           = '55'
5 + 5               = 10
int("5") + int("5") = 10

10 / 4  = 2.5
10 // 4 = 2
10 % 4  = 2

True + True       = 2
isinstance(True, int) = True
0.1 + 0.2         = 0.30000000000000004
0.1 + 0.2 == 0.3  = False
isclose           = True
2 ** 100          = 1267650600228229401496703205376

Toward the bottom you will see 0.1 + 0.2 comes out as 0.30000000000000004, and the comparison with 0.3 is false. Python is not being silly. The same result appears in JavaScript, Java, C and nearly every language, because it comes from how binary stores fractions.

Here is the analogy I use with students. Try writing one third in decimal. You get 0.3333… and it never ends. You can write as many 3s as you like, but you can never write it exactly. Now notice that one third is a perfectly ordinary number. It is only awkward because our counting system is base ten, and ten is not divisible by three.

Computers use base two. In base two, one tenth is the awkward one. It becomes 0.0001100110011… repeating forever, so it has to be cut off somewhere. What the computer actually stores for 0.1 is a very slightly different number. I printed it:

from decimal import Decimal
import struct, sys

print("0.1 is really stored as:", Decimal(0.1))
print("0.5 is stored as       :", Decimal(0.5), "(a power of two, so exact)")
print("0.75 is stored as      :", Decimal(0.75))
bits = format(struct.unpack(">Q", struct.pack(">d", 0.1))[0], "064b")
print("64 bits of 0.1:", bits[0], bits[1:12], bits[12:])
print("largest float  :", sys.float_info.max)
print("smallest float :", sys.float_info.min)
print("digits of care :", sys.float_info.dig)
import math
print()
print("gap between neighbouring floats:")
print("  near 1             :", math.ulp(1.0))
print("  near 1e15          :", math.ulp(1e15))
print("  near 2**53 (9e15)  :", math.ulp(2.0 ** 53))

Output:

0.1 is really stored as: 0.1000000000000000055511151231257827021181583404541015625
0.5 is stored as       : 0.5 (a power of two, so exact)
0.75 is stored as      : 0.75
64 bits of 0.1: 0 01111111011 1001100110011001100110011001100110011001100110011010
largest float  : 1.7976931348623157e+308
smallest float : 2.2250738585072014e-308
digits of care : 15

gap between neighbouring floats:
  near 1             : 2.220446049250313e-16
  near 1e15          : 0.125
  near 2**53 (9e15)  : 2.0

So the stored 0.1 is 0.1000000000000000055511… Not exactly one tenth, but close enough that you normally never notice. Add two such slightly-off values and the tiny errors can show up at the sixteenth or seventeenth digit. Notice too that 0.5 and 0.75 are stored exactly, because they are built from powers of two (a half, a quarter). A float is only exact when the fraction is made of halves, quarters, eighths and so on.

Floats lose precision as they get big

There is a second quirk. A 64-bit float has only about 15 to 16 reliable decimal digits, and the gaps between neighbouring floats grow as the numbers grow. That is the output at the bottom of the block above: near 1, neighbouring floats are about 0.0000000000000002 apart. Near 9 quadrillion, they are 2 apart, so the float simply cannot represent every whole number.

Near 1: the next float is 0.00000000000000022 awayNear 1,000,000,000,000,000: the next float is 0.125 awayNear 9,007,199,254,740,992: the next float is 2 awayBar length is the size of the gap on a log scale, 64-bit floats.
The distance between one float and the next gets larger as the numbers get larger (log scale of the gap, longer bar means wider gap).

The practical rule: beyond 253, which is 9,007,199,254,740,992, floats skip whole numbers. In JavaScript, where every number is a float, this is why the biggest integer you can trust is 9,007,199,254,740,991. It is also why you should never store something like a 19-digit ID in a float.

How to compare floats safely

Because of those tiny errors, never ask whether two floats are exactly equal after calculation. Ask whether they are close enough. In Python, the function math.isclose does it. In other languages, take the absolute difference and compare it with a small tolerance, such as 0.000001, chosen to suit your problem. This one habit prevents a surprising number of bugs.

Booleans: the simplest type of all

A boolean has exactly two possible values: true or false. It is named after the mathematician George Boole, who built a branch of logic around exactly this idea in the nineteenth century. In everyday life, a boolean is any yes/no fact: is the user logged in, is the light on, has the invoice been paid, is the stock above its limit.

Booleans are the type that makes decisions possible. Every if statement and every loop condition eventually boils down to a boolean. When you write “if age is at least 18”, the comparison produces true or false, and the program picks a path based on it.

Storage: one bit of information, one byte of space

A boolean carries one bit of information, since there are only two answers. Yet most systems store it in a whole byte, because computers address memory in bytes and it is faster to read a full byte than to dig out a single bit. The little table at the end of the overflow code printed this: a boolean takes 1 byte, the same as a tiny integer. Programmers who need to store millions of flags sometimes pack eight of them into a single byte for exactly this reason.

Booleans in Python are secretly integers

In Python, True behaves like 1 and False behaves like 0. The code above showed that True + True gives 2 and that a boolean passes the test for being an integer. That is occasionally handy, for example counting how many items in a list satisfy a test by adding up their true/false results. It is also a source of odd bugs, so keep it in mind.

A more important trap involves text. The string “False” is not the boolean False. In Python, any non-empty string counts as true, so bool(“False”) is True. This bites people reading settings from a file or a web form, where everything arrives as text. Convert the value deliberately, instead of trusting it.

Why they differ: a side-by-side view

With all three in front of you, the differences are easier to see in one place.

PropertyIntegerFloatBoolean
HoldsWhole numbersNumbers with a fractionTrue or false
Example42, −73.14, 36.6True, False
Typical size1, 2, 4 or 8 bytes4 or 8 bytes1 byte
Exact?Yes, within its rangeNo, about 15 digitsYes
RangeLimited by widthEnormous, but coarseTwo values
Main dangerOverflowRounding errorConfusing text with true/false
Best forCounting, IDs, money in small unitsMeasurements, scienceConditions, flags

Notice that each type’s strength and weakness come from the same decision. Integers are exact because they cannot hold fractions. Floats can hold fractions because they give up exactness. Booleans are simple because they hold almost nothing. There is no free lunch, just a trade-off chosen for each job.

The fourth type that fools people: strings

Strictly speaking this article is about three types, but one more deserves a mention because beginners confuse it with integers all the time. A string is text: letters, digits, spaces, anything in quotation marks. The string “5” and the integer 5 look alike but behave very differently. Adding the two integers 5 + 5 gives 10. Adding the two strings “5” + “5” gives “55”, the text glued together.

This matters whenever data comes from outside your program. Form fields, CSV files and web pages deliver everything as text. If you forget to convert with int() or float(), you will get joined-up text instead of sums, or an error. The sample output earlier shows all three results side by side.

The reverse mistake is just as common. A phone number, PIN code or postal code is made of digits, but you never add or average them. Store them as strings. A PIN of 0482 stored as an integer becomes 482, and the leading zero is gone for good.

The money rule: never use floats

If there is one lesson from this article that will save you real trouble, it is this: do not store money in floats. It is the most common serious data-type mistake in shops, billing systems and spreadsheets. Here is a test. A shop sells 1,000 sweets at 0.10 each. I added the price one thousand times three ways:

from decimal import Decimal

# A shop sells 1,000 sweets at 0.10 each. Add the prices one by one.
total_float = 0.0
for _ in range(1000):
    total_float += 0.10
print("float total   :", total_float, "| equals 100.0?", total_float == 100.0)

total_dec = Decimal("0")
for _ in range(1000):
    total_dec += Decimal("0.10")
print("Decimal total :", total_dec, "| equals 100?", total_dec == 100)

paise = 0
for _ in range(1000):
    paise += 10                      # store money as whole paise (integers)
print("integer paise :", paise, "-> rupees", paise / 100)

print()
print("19.99 * 3       =", 19.99 * 3)
print("1999 * 3 paise  =", 1999 * 3, "-> 59.97")

Output:

float total   : 99.9999999999986 | equals 100.0? False
Decimal total : 100.00 | equals 100? True
integer paise : 10000 -> rupees 100.0

19.99 * 3       = 59.97
1999 * 3 paise  = 5997 -> 59.97

The float total is 99.9999999999986 and fails the check against 100. The Decimal type, which stores decimal digits exactly, gets 100.00. And whole units, in this case paise, get exactly 10,000, which is 100 rupees. The tiny 0.0000000000014 error would never show up on a receipt, but it can break an equality check, trip a reconciliation report or make a daily total off by a cent when multiplied by millions of transactions.

To be fair, floats do not always misbehave. At the bottom of the output, 19.99 × 3 prints a clean 59.97. That is the danger: it works nearly every time, so you trust it, and then one day it does not. Whenever correctness matters, use one of two safe approaches:

  • Integer smallest units. Store 19.99 rupees as 1999 paise, or 19.99 dollars as 1999 cents. Calculate in whole numbers, and divide by 100 only when displaying.
  • A decimal type. Python has Decimal, Java has BigDecimal, and most databases have a DECIMAL or NUMERIC column. These store decimal digits exactly.

Data types in everyday life

You do not need to be a programmer to meet these types. Click a tab to see five everyday situations and which type fits each one, and why.

Stadium crowd

A cricket ground counts spectators through the turnstiles. What type should the counter be?

TypeInteger
Example52,314
WhyNo half people
RiskOverflow if too narrow

The right type. Counting whole things is the textbook job for an integer. Every entry adds exactly 1, and the total is exact no matter how many people arrive. The only thing to check is the width: a 16-bit counter tops out at 32,767, which a big stadium would pass, so a 32-bit or 64-bit integer is the safe choice.

Shop price

A shop sells an item for 19.99 rupees. How should the price be stored so the day’s total is right?

TypeWhole paise
Example1999
Float sum99.9999999999986
Exact sum10000

The right type. Store 1999 paise as an integer, calculate in paise and divide by 100 only for display. In my test, adding 0.10 a thousand times in a float gave 99.9999999999986, while adding 10 paise a thousand times gave exactly 10,000. A decimal type is the other safe route.

Body temperature

A thermometer app records 36.6 degrees Celsius. Which type fits?

TypeFloat
Example36.6
PrecisionAbout 15 digits
CompareWith a tolerance

The right type. A temperature is a measurement, so a float is right: it can hold a fraction, and a tiny error in the sixteenth digit is irrelevant for a thermometer that is only accurate to a tenth of a degree. When checking whether a reading equals a target, test whether it is close enough instead of testing for exact equality.

Logged in?

A website needs to remember whether a visitor is signed in. What type holds that fact?

TypeBoolean
ValuesTrue or False
InformationOne bit
Trap“False” is truthy

The right type. A yes/no fact is a boolean. It decides whether to show the account page or the login form. The classic trap is a setting saved as text: in Python, bool(“False”) is True, because any non-empty string counts as true. Convert text to a boolean on purpose.

Phone number

A form collects a phone number such as 09876543210. Should it be a number type?

TypeString
Example09876543210
As integer9876543210
LostThe leading 0

The right type. No. You never add or average phone numbers, so they are labels, and labels belong in strings. Stored as an integer, the leading zero disappears and the value changes. The same advice covers PIN codes, postal codes, account numbers and ID numbers.

Choosing the right type: a quick decision guide

When I design a new database table or a form, I go through the same short list. Read the questions top to bottom and stop at the first yes.

1. Is it a yes or no flag(on/off, paid/unpaid)?yesBooleanTrue or Falseno2. Are you counting wholethings, with no fractions?yesIntegerwatch the widthno3. Is it money, or must thedecimal digits be exact?yesWhole paise or cents,or a Decimal typeno4. Is it a measurement wherea tiny error is fine?yesFloatcompare with a toleranceno5. Is it a label, like a phonenumber, PIN or name?yesStringtext, never arithmetic
A practical way to choose a type. When in doubt about money, pick whole units.

Converting between types

Programs constantly change a value from one type to another, and some conversions lose information. Knowing which is useful.

  • Integer to float is usually safe for small numbers. 7 becomes 7.0. Very large integers can lose digits, as we saw past 253.
  • Float to integer throws away the fraction. In Python, int(3.9) gives 3 and int(−3.9) gives −3, since it chops toward zero instead of rounding. If you want rounding, call round() on purpose.
  • Rounding has quirks. Python’s round() uses “round half to even”, so round(2.5) is 2 and round(3.5) is 4. It is designed to avoid a bias when many values are rounded, but it surprises people who expect 2.5 to become 3.
  • String to number needs int() or float(), and it fails with an error if the text is not a valid number. Always handle that case when reading user input.
  • Anything to boolean follows the language’s own rules. In Python, zero, empty text and empty lists count as false, and almost everything else counts as true, including the string “False”.
  • Division is a type decision too. In Python, 10 / 4 is 2.5, a float, while 10 // 4 is 2, whole-number division, and 10 % 4 is the remainder, 2. In some older languages, dividing two integers silently gives an integer, which has caused many off-by-a-fraction bugs.

Common mistakes and how to avoid them

  • Using floats for money. Use integer paise or cents, or a decimal type.
  • Comparing floats with ==. Compare with a tolerance instead.
  • Storing IDs, phone numbers and PINs as numbers. If you never do arithmetic on it, it is probably a string.
  • Ignoring the width of an integer. If a counter could ever pass about two billion, use a 64-bit integer from the start.
  • Trusting text as a boolean. The text “false” is true in most languages. Convert it deliberately.
  • Forgetting that form data is text. Everything from a web form arrives as a string until you convert it.
  • Assuming integer division behaves the same everywhere. Check how your language divides whole numbers.
  • Storing huge whole numbers in floats. Beyond about nine quadrillion, floats skip numbers.

A mental model that sticks

If you remember only one picture, make it this. An integer is a staircase: you are on step 4 or step 5, never in between, and each step is exactly where it says it is. A float is a ramp with markers painted on it: you can stand anywhere, but the markers are only approximate, and they are spaced further apart as you climb. A boolean is a light switch: on or off, nothing else. Pick the staircase when you count, the ramp when you measure and the switch when you decide.

Practice problems with answers

Try each one before you tap to check.

1. Which type should hold the number of items in a shopping cart?

Integer. You count whole items, and there is no such thing as 2.5 items.

2. What do 10 / 4 and 10 // 4 give in Python?

2.5 and 2. The single slash gives a float, and the double slash divides and keeps only the whole part.

3. Why is 0.1 + 0.2 not exactly 0.3?

One tenth has no exact binary form, so the stored 0.1 and 0.2 are both slightly off. Their sum is 0.30000000000000004.

4. A signed 8-bit integer holds 127. What is the value after adding 1?

−128. The pattern 01111111 becomes 10000000, which is read as the most negative value.

5. What does True + True equal in Python?

2. In Python, True counts as 1 and False counts as 0.

6. Which type suits the PIN 0482, and why?

A string. You never do arithmetic on a PIN, and storing it as an integer would drop the leading zero and leave 482.

7. How would you store a price of 19.99 rupees safely?

As the integer 1999 paise, or as a Decimal. Divide by 100 only when you display it.

Test yourself: five quick questions

Tap a question to reveal the answer. The correct option is marked.

Which type is best for counting the people in a room?
  1. Integer
  2. Float
  3. Boolean
  4. String

People come in whole units, so an integer is exact and natural.

What does a signed 8-bit integer become when you add 1 to 127?
  1. 128
  2. 0
  3. −128
  4. 255

It wraps around. Binary 01111111 plus one is 10000000, which a signed integer reads as −128.

Why does 0.1 + 0.2 give 0.30000000000000004?
  1. Python has a bug
  2. 0.1 cannot be stored exactly in binary
  3. Floats cannot add
  4. The computer rounds up on purpose

One tenth repeats forever in binary, so it must be cut off. The tiny errors show up in the result.

What is bool(“False”) in Python?
  1. False
  2. An error
  3. None
  4. True

Any non-empty string counts as true, including the text “False”. Convert text to a boolean deliberately.

How should you store money to avoid rounding errors?
  1. As a float with two digits
  2. As whole paise or cents, or a Decimal
  3. As a boolean
  4. As a string only

Whole units are exact. Floats are not, as 1,000 additions of 0.10 showed: 99.9999999999986.

Frequently asked questions

What is the difference between an integer and a float?

An integer is a whole number with no fractional part and is stored exactly. A float has a decimal point and is stored as digits plus an exponent, which allows fractions and huge ranges but only approximate accuracy.

Why do floats have rounding errors?

Computers store numbers in binary. Some decimals, such as 0.1, repeat forever in binary, so they are cut off and stored as a nearby value. The small error can appear after calculations.

What is a boolean used for?

A boolean holds true or false and drives decisions in code. Every if statement and loop condition ends up as a boolean, and flags such as is_logged_in or has_paid use the type directly.

What is integer overflow?

When a calculation produces a value too large for the integer’s fixed width. In many languages it wraps around, so the biggest positive value plus one becomes the most negative value.

Should I use float or double?

Both are floating-point types. Float usually means 32 bits, with about 7 reliable digits, and double means 64 bits, with about 15. Most modern code uses double unless memory is tight. Python’s float is a 64-bit double.

Do all programming languages have these types?

Most do, but names and behaviour differ. Python integers grow without a fixed limit, C and Java use fixed widths, and JavaScript has a single number type that is a 64-bit float. Always check how your language handles each type.

Key takeaways

  • A data type tells the computer how many bits a value uses, how to read them and which operations make sense.
  • Integers are exact whole numbers, but a fixed width can overflow: 127 + 1 wraps to −128 in a signed 8-bit integer, and the 32-bit Unix clock runs out in January 2038.
  • Floats handle fractions and huge ranges, but they are approximate. 0.1 + 0.2 gives 0.30000000000000004 because 0.1 has no exact binary form.
  • Booleans hold true or false and drive every decision. The text “False” is not the boolean False.
  • Never store money in floats: my test of 1,000 additions of 0.10 gave 99.9999999999986. Use whole paise or cents, or a decimal type.
  • If you never do arithmetic on a value, such as a phone number or PIN, store it as a string.
data typesintegersfloating pointbooleansprogramming for beginnersfloating point precisioninteger overflow

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *