Friday, November 9, 2018

PHP Integers, Floats and Number Strings

PHP Integers, Floats and Number Strings

Working with numbers in PHP seems to be a trivial concept but it can be quite confusing. It looks easy at first because PHP provides automatic type conversion. For example, you can assign an integer value to a variable and the type of that variable will be an integer. On the next line, you can assign a string to the same variable and the type will change to a string. Unfortunately, this automatic conversion can sometimes break your code.

There are a lot of types for numeric values as well. In this tutorial, you'll learn about  integers and floats in PHP, as well as the functions which can be used to determine the type of numbers that we are dealing with and convert between them. You'll also learn how to convert integers and floats to and from numerical strings.

Different Types of Numbers in PHP

Integers

The most basic type of number in PHP is the integer. As you might already know, integers are numbers without any decimal part. For example, 2 is an integer and so is 235298 or -235298. On the other hand, 2.0 and 3.58 are floats. We will discuss them in more detail later.

One important thing to remember is that it is not necessary that a number be of type int if it does not have a decimal part. For example, 16 * 2.5 is exactly 40 but the type of this result will still be a float. When you are multiplying numbers, the final result will be of type float if at least one of the operands was a float. It doesn't matter if the final number has a decimal part or not.

Also, the maximum possible value an integer can have in PHP on your system can be obtained using the constant PHP_INT_MAX. A value greater in magnitude than the value returned by PHP_INT_MAX will be stored as a float even if it looks like an integer.

Generally, you would expect the result of multiplication of two variables of type int to be of type int. However, it is not true in case of overflow. Multiplication of five or six different numbers can easily take you outside the bounds of int type. For example, the result of 128*309*32*43*309 is a float on my system because it exceeds the value of PHP_INT_MAX which is 2147483647.

You can use the is_int($value) function to check if a number is of type integer. There are two aliases of this function called is_integer($value) and is_long($value). Both of them will give the same result.

Floats

The next most common type of number that you will deal with is a float. Unlike integers,  which were simply numbers without decimal points in most cases, a number of type float can be represented in a variety of ways. The values 3.14, 12.0, 5.87E+10 and 3.56E-5 are all floats.

PHP will automatically convert a number to type float whenever decimals or very large numbers are involved. The float type can commonly store numbers with magnitude approximately equal to 1.7976931348623E+308. However, this is platform dependent.

The value 1.7976931348623E+308 may seem like a very large value—and it is!—but floats have a maximum precision of only about 14 digits. Any number with more digits than that will lose its precision. That means you can store a very large number, but you won't be able to keep the information about its exact value—in many cases, a float is only an approximation.

There are two functions which can be used to determine if the value you are dealing with is a float. These functions are is_float() and is_double(). Actually, is_double() is just an alias of is_float() so you can use any one of them and get the same result.

Infinity and NaN

There are two more kinds of numerical values that you might have to deal with when writing programs related to Mathematics. These values of infinity and NaN (not a number). Both these values require a little explanation because they are different from what you might expect.

Infinity in PHP is different from infinity in real life. In PHP, any numerical value above approximately PHP_FLOAT_MAX on a platform is considered infinity. So, 1.8e308 will give you float(INF) on var_dump(). You can check if a numerical value is finite or infinite using the is_finite() and is_infinite() functions.

Similarly, NaN stands for Not a Number but it doesn't check if a value is numerical or not. The value NaN is used for result of mathematical operations which are not possible in mathematics. For example, log(-1) will be NaN. Similarly, acos(5) will also be NaN. You can check if the value returned by a mathematical operation is not number by using the function is_nan().

Numerical Strings in PHP

Just like PHP dynamically change the type of different numbers based on how their values are used or assigned, it can also infer the value of different numerical strings for you to convert them to numbers.

The function is_numeric() can help you determine if a string or variable is indeed numeric or not. This function will return true for numbers written in octal, binary or hexadecimal notation. It will also return true if the numbers are written in exponential notation like +16.52e39.

Starting from PHP 7.0.0, when you pass a string to is_numeric(), it only returns true if the string consists of an optional sign, some digits, an optional decimal and an optional exponential part. This means that a numerical string written in hexadecimal or binary format will return false from PHP 7.0.0 onward.

PHP will implicitly cast any valid numerical string to a number when need arises. The following examples should help you understand this process better.

As you can see, all valid numerical string were converted to their respective values before addition or other operations were performed. The type of $num in the end depends on its final value.

In the last case, the hexadecimal string "0xfedd24" is not converted to its decimal value because PHP 7 does not consider it to be a valid numerical string.

Casting Strings and Floats to Integers

Every now and then, you will need to cast one type of numerical values into another. PHP has a variety of functions and techniques to do so. Most of the time, the conversion will be implicit and you won't have to worry about it. However, if you have to do the conversion explicitly techniques mentioned here will definitely help.

You can use (int) or (integer) to convert any value to an integer. In case of floats, the values will always be rounded towards zero. Another way to cast strings and floats to integers is with the help of intval() function. Both (int) and intval() work in exactly the same manner.

You should note that casting overflowing strings to integers will set the final value to the maximum permissible integer value. However, casting a float whose value is more than the maximum permissible integer value will result in the value oscillating between -2147483648 and 2147483647!

In certain situations, you might need to deal with very large numbers without loosing any precision. For example, it is impossible to get accurate result of multiplication of 987233498349834828 and 3487197512 using the * operator. It will give you 3.4426781992086E+27 after float conversion. Calculating the actual answer, which is 3442678199208600117812547936, will require use of libraries like BCMath. BCMath works by storing numbers as strings and doing arithmetic operations on them manually. Just remember that if you use BCMath, you will be dealing with strings instead of integers and floats.

Certain libraries will want you to only pass numbers of type int to their methods but you might unknowingly supply them a float value. This might happen because the value seems like an int because it doesn't have a decimal part. This would almost certainly result in an error if the library uses a function like is_int() to check if the passed number is of integer type. In such cases, it is always wise to first cast that number to int using either (int) or intval() and then pass it to any functions or methods of the library.

One example of when such a situation could come up would be when you are dealing with Mathematical functions like floor() and ceil() etc. floor() and ceil() will always return a float, even if you pass them an int!

One problem with casting floats to integers is that you will lose the decimal part of the numbers. This may or may not be desirable. In such cases, you can use functions like floor() and only cast the number to int type if its actual value is equal to the value returned by floor().

Let's say you have a library which allows you to do fractional arithmetic and it throws exceptions when you pass a number to its setNumerator() method that is not of type int. A variety of operations might turn a number in type float even if it is still an integer within the minimum and maximum bounds of type int. Using something like the code above will help you deal with such cases easily.

Final Thoughts

This tutorial has covered different ways in which PHP stores numbers and how you can determine if a number of a particular type. For example, you can use functions like is_int() and is_float() to determine the type of a number and proceed accordingly.

As you saw in the tutorial, PHP supports automatic type conversion. This means that sometimes smaller integers like 5 or 476 could have been stored as floats without you realizing it. Using these numbers in functions which only accept int values might result in exceptions or errors. We learned that a simple solution to this problem is be to explicitly cast such numbers to int if they don't have a decimal part and their values don't change upon casting.

After reading this tutorial, you should be able to determine the type of a number or the final type of a result after using a variety of operations using predefined functions and also explicitly cast them to a specific type after doing some checks.

As always, if you have any questions or additional tips, you are welcome to comment.


No comments:

Post a Comment