Numeric Functions
PHP offers various arithmetic operators for performing mathematical operations. Sometimes, these operators are not enough. Luckily, there are a handful of functions for working with numbers.
Rounding Numbers
PHP offers a few functions to help you round numbers. Using the correct function will give you the best results. Let's explore some of them.
round()
This is the standard rounding function. It rounds a floating-point number to its nearest integer. If the fractional part of the number is 0.5
or higher, it rounds up; if it's less than 0.5
, it rounds down. You can also specify the number of decimal places to which you want to round.
Learn more about the round()
function here.
echo round(3.6); // Outputs: 4
echo round(3.4); // Outputs: 3
echo round(3.14159, 2); // Outputs: 3.14
Precision
The round(
) function allows you to specify a second argument for precision, which determines how many decimal places to round to.
In this example, $number is initially 3.14159
. We call round($number, 2)
, which means "round $number to the nearest hundredth (two decimal places)". The result is 3.14
. This could be useful in a number of situations, like when dealing with monetary values where you might need to round to the nearest cent.
You can also round to more decimal places. In the second use of the round()
function, we've rounded $number
to 4
decimal places, resulting in 3.1416
.
By using the second argument of the round()
function, you can control the precision of the rounding to suit your needs.
$number = 3.14159;
// Round to 2 decimal places
$rounded1 = round($number, 2); // $rounded becomes 3.14
// Round to 4 decimal places
$rounded2 = round($number, 4); // $rounded becomes 3.1416
ceil()
This function always rounds a number up to the next highest integer, regardless of the value of the fractional part.
Learn more about the ceil()
function here.
echo ceil(3.4); // Outputs: 4
echo ceil(3.6); // Outputs: 4
floor()
This function always rounds a number down to the next lowest integer, regardless of the value of the fractional part.
Learn more about the floor()
function here.
echo floor(3.4); // Outputs: 3
echo floor(3.6); // Outputs: 3
Remember, these functions return a rounded value but do not change the original variable's value.
Avoid type casting
Type casting is a great way to convert a float into an integer. However, it does not round values during this process.
Type casting a floating-point number to an integer in PHP always truncates the decimal part, effectively performing a floor()
operation. This is fine for some scenarios, but it may not always give you the results you want. Here are a few reasons why you might choose to use round()
, ceil()
, or floor()
instead:
- Different Rounding Needs: If you need to round up no matter what the decimal is (i.e.,
3.1
becomes4
),ceil()
is what you need. If you need standard rounding rules (i.e.,3.5
becomes4
, and3.4
becomes3
), then you should useround()
. Type casting to integer can't provide these options. - Precision Control: With
round()
, you can control the precision of rounding with a second parameter, which lets you specify the number of decimal places. Type casting to integer can't do this. - Clearer Intent: Using
round()
,ceil()
, orfloor()
makes your code clearer. Someone reading your code can immediately understand that you're performing a rounding operation. With typecasting, it may not be immediately clear what your intent is.
For example:
// Type casting to an integer
$number = (int) 3.6; // $number becomes 3
// Using rounding functions
$rounded = round(3.6); // $rounded becomes 4
In the above examples, type casting truncates the decimal part, while round()
actually rounds the number to its nearest integer.
Negative numbers
Rounding negative numbers works similarly to rounding positive numbers. In PHP, as well as in mathematics in general, we consider "down" to be in the direction of negative infinity and "up" to be in the direction of positive infinity.
Let's look at how PHP's rounding functions deal with negative numbers:
round()
: Theround()
function works with negative numbers in the same way it does with positive numbers. It rounds a negative floating-point number to its nearest integer. For example,round(-3.4)
would round to-3
, because-3
is closer to-3.4
than-4
is. Conversely,round(-3.6)
would round to-4
, because-4
is closer to-3.6
than-3
is.floor()
: Thefloor()
function always rounds down or towards negative infinity. This meansfloor(-3.4)
would round to-4
. Even though-3
is numerically closer to-3.4
, "rounding down" means moving towards a more negative number.ceil()
: Theceil()
function always rounds up or towards positive infinity. Soceil(-3.4)
would round to-3
. Even though-4
is numerically closer to-3.4
, "rounding up" means moving towards a less negative (or more positive) number.
Generating a Random Number
The mt_rand()
function is a function that generates a random integer. The name "mt_rand" stands for "Mersenne Twister Random," referring to the Mersenne Twister algorithm it uses to generate random numbers. This algorithm is known for generating random numbers quickly and with better statistical properties.
Here's how to use it:
echo mt_rand(); // Outputs a random integer between 0 and mt_getrandmax()
If you want to generate a random number within a specific range, you can specify the minimum and maximum values as parameters, like so:
echo mt_rand(1, 50); // Outputs a random integer between 1 and 50
Don't use for cryptography
Numbers generated by mt_rand()
are pseudo-random. That means they're generated by an algorithm and, while appearing random, are not suitable for cryptographic use.
Verifying Numbers
Sometimes you need to verify you're working with a number. Numbers can come in the form of a string, which can make things tricky. Luckily, there's the is_numeric()
function.
The is_numeric()
function in PHP is used to determine whether a variable is a number or a numeric string. In other words, it checks if a value is a number or a string that contains a numeric value.
Here's a basic usage:
$isNum = is_numeric(123); // true because 123 is a number
echo $isNum ? 'true' : 'false'; // Outputs: true
$isNum = is_numeric("123"); // true because "123" is a numeric string
echo $isNum ? 'true' : 'false'; // Outputs: true
$isNum = is_numeric("123abc"); // false because "123abc" is not a numeric string
echo $isNum ? 'true' : 'false'; // Outputs: false
In the above example, is_numeric()
returns a boolean true
if the value is a number or numeric string and false
otherwise.
Remember, this function is handy when you're handling user input or data from an unknown source, and you need to check whether a value can be treated as a number.
Formatting Numbers
PHP stores numbers without separators (aka commas). If you need to output a number, you might want to add commas for readability.
The number_format()
function in PHP is used to format a number with grouped thousands. This means it takes a number and formats it in a way that's easier to read, especially for large numbers, by adding commas (or other characters you specify) between every group of thousands.
Here's a simple usage:
echo number_format(123456789); // Outputs: 123,456,789
In the above example, number_format()
adds a comma after every group of three digits counted from the right, making the number easier to read.
The function can also accept more parameters to control the number of decimal points and what characters to use for decimal points and thousands separators.
Here's a more complex example:
echo number_format(123456789.12345, 2, ".", ",");
// Outputs: 123,456,789.12
In this example, the first parameter is the number we want to format. The second parameter is the number of decimal points we want in the output (2 in this case). The third parameter is the character we want to use for the decimal point (a period in this case). The fourth parameter is the character we want to use as the thousands separator (a comma in this case).
Key takeaways
- The
round()
function is the most commonly used function for rounding in PHP. It rounds a floating-point number to its nearest integer. It can also round to a specified number of decimal places if provided with a second argument. - : The
floor()
function rounds a number down, returning the next lowest integer value. - The
ceil()
function rounds a number up, returning the next highest integer value. - Rounding functions provide more control over the output than simply casting a float to an integer, which always rounds down.
- All these functions also work with negative numbers. The
floor()
function still rounds down (toward negative infinity), andceil()
still rounds up (toward positive infinity), even when dealing with negative numbers. - Functions like
is_numeric()
allow you to check if a variable is a number or a numeric string, which can be crucial when handling user input or data from unknown sources. - Functions like
number_format()
can make numbers more human-readable by adding separators between groups of thousands or controlling the number of decimal places. - PHP provides functions like mt_rand() for generating random numbers.