11 Vote

PHP: Rounding Numbers

Tutorial by Stefan Trost | 2014-02-02 at 17:02

Using the functions  round(), ceil() and floor(), you can round a number in PHP.

While ceil() always rounds up a floating point number and floor() always rounds down numbers, round() rounds depending on the decimal place.

echo ceil(7.1);   // 8
echo ceil(7.7);   // 8

echo floor(7.1);  // 7
echo floor(7.7);  // 7

echo round(7.1);  // 7
echo round(7.7);  // 8

Rounding Precision

Optionally, we can pass a second parameter to round() indicating the number of decimal places to which should be rounded. If we omit this parameter like the first example, it is always rounded to 0 decimal places.

echo round(7.1234, 0);    // 7
echo round(7.1234, 1);    // 7.1
echo round(7.1234, 2);    // 7.12

echo round(123.123, -1);  // 120
echo round(123.123, -2);  // 100

Passing a negative value for the rounding precision is making it possible to around to the appropriate position before the decimal point. In this example, for instance, we are rounding by "-1" to the tens digit and by "-2" to the hundreds place.

Text Output

If you would like to output or echo point numbers as text, in many cases, it is better to use functions like number_format() or sprintf() for the text output. For example, if you would like to keep two fixed decimal places in the output, this is not possible with round().

For example, using "echo round(4,2)" would result in the string "4". To ensure an output like "4.00", we should better use number_format() or sprintf(), because round() already changes a number variables and does not have any influence on the output.

ReplyPositiveNegative

About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.