PHP round() Tutorial 🎯

beginner
9 min

PHP round() Tutorial 🎯

Welcome to our PHP round() tutorial! In this lesson, we'll dive into the world of number manipulation in PHP, focusing on the round() function. This tutorial is designed for both beginners and intermediate learners, so let's get started!

What is the PHP round() function? πŸ“

The round() function in PHP is used to round a given number to a specified number of decimal places. It's a handy function when you want to present numerical data in a more readable format.

php
round(number, decimal_places);
  • number: The number you want to round.
  • decimal_places: The number of decimal places you want to keep (optional, defaults to 0).

Rounding Numbers 🎯

Let's see how to round numbers using the round() function with examples.

Rounding to the nearest whole number πŸ’‘

To round a number to the nearest whole number, simply use the round() function without specifying the number of decimal places.

php
<?php $number = 3.715; $rounded = round($number); echo $rounded; // Output: 4 ?>

Rounding to a specific number of decimal places πŸ’‘

If you want to round a number to a specific number of decimal places, specify the number of decimal places as the second argument.

php
<?php $number = 123.45678; $rounded = round($number, 2); echo $rounded; // Output: 123.46 ?>

Pro Tips πŸ’‘

  1. To round down to the nearest integer, use the floor() function.
php
<?php $number = 3.715; $roundedDown = floor($number); echo $roundedDown; // Output: 3 ?>
  1. To round up to the nearest integer, use the ceil() function.
php
<?php $number = 3.285; $roundedUp = ceil($number); echo $roundedUp; // Output: 4 ?>

Quiz 🎯

Quick Quiz
Question 1 of 1

Which function is used to round a number to a specified number of decimal places in PHP?


That's it for our PHP round() tutorial! Now you know how to round numbers using the round() function in PHP, as well as some pro tips for rounding down and up. Happy coding! πŸŽ‰