PHP · December 19, 2023

PHP Function:round

PHP Function: round

In PHP, the round() function is a powerful tool that allows developers to round a floating-point number to a specified precision. This function is particularly useful when dealing with mathematical calculations or when displaying numbers in a more user-friendly format.

Syntax

The syntax for the round() function is as follows:

round(float $number, int $precision = 0, int $mode = PHP_ROUND_HALF_UP): float

The $number parameter represents the floating-point number that you want to round. The $precision parameter specifies the number of decimal places to round to, and it is optional. By default, it is set to 0, which means rounding to the nearest whole number. The $mode parameter determines the rounding mode and is also optional. It defaults to PHP_ROUND_HALF_UP, which rounds up when the decimal is 5 or higher.

Examples

Let's explore some examples to understand how the round() function works:

Example 1: Basic Rounding

$number = 3.14159;
$roundedNumber = round($number);

echo $roundedNumber; // Output: 3

In this example, we have a floating-point number $number with a value of 3.14159. By calling the round() function without specifying the precision, the number is rounded to the nearest whole number, resulting in 3.

Example 2: Rounding to a Specific Precision

$number = 3.14159;
$roundedNumber = round($number, 2);

echo $roundedNumber; // Output: 3.14

In this example, we use the round() function with a precision of 2. As a result, the number is rounded to two decimal places, giving us 3.14.

Example 3: Rounding with Different Modes

$number = 3.5;
$roundedNumber1 = round($number, 0, PHP_ROUND_HALF_UP);
$roundedNumber2 = round($number, 0, PHP_ROUND_HALF_DOWN);

echo $roundedNumber1; // Output: 4
echo $roundedNumber2; // Output: 3

In this example, we have a number 3.5. By using the round() function with different rounding modes, we can control how the number is rounded. In the first case, we use PHP_ROUND_HALF_UP, which rounds up when the decimal is 5 or higher, resulting in 4. In the second case, we use PHP_ROUND_HALF_DOWN, which always rounds down, giving us 3.

Summary

The round() function in PHP is a versatile tool for rounding floating-point numbers to a specified precision. It allows developers to control how numbers are rounded and is particularly useful in mathematical calculations and formatting numbers for display. By understanding the syntax and examples provided, you can leverage the power of the round() function in your PHP projects.

For more information about VPS hosting solutions, visit Server.HK.