O'Reilly logo

PHP Cookbook, 2nd Edition by David Sklar, Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.2e308 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 correct plus or minus a small ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required