Chapter 2. Numbers
Introduction
In everyday life, numbers are easy to identify. Theyâre 3:00 P.M., as in the current time, or $1.29, as in the cost of a pint of milk. Maybe theyâre like Ï, the ratio of the circumference to the diameter of a circle. They can be pretty large, like Avogadroâs number, which is about 6 Ã 1023. In PHP, numbers can be all these things.
However, PHP doesnât treat all these numbers as ânumbers.â Instead, it breaks them down into two groups: integers and floating-point numbers. Integers are whole numbers, such as â4, 0, 5, and 1,975. Floating-point numbers are decimal numbers, such as â1.23, 0.0, 3.14159, and 9.9999999999.
Conveniently, most of the time PHP doesnât make you worry about
the differences between the two because it automatically converts
integers to floating-point numbers and floating-point numbers to
integers. This conveniently allows you to ignore the underlying details.
It also means 3/2
is 1.5
, not 1
,
as it would be in some programming languages. PHP also automatically
converts from strings to numbers and back. For instance, 1+"1"
is 2
.
However, sometimes this blissful ignorance can cause trouble. First, numbers canât be infinitely large or small; thereâs a minimum size of 2.2eâ308 and a maximum size of about 1.8e308.[1] If you need larger (or smaller) numbers, you must use the BCMath or GMP libraries, which are discussed in Recipe 2.14.
Next, floating-point numbers arenât guaranteed to be exactly correct but only ...
Get PHP Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.