How to round numbers with PHP

Josh Sherman
1 min read
Software Development PHP

Rounding numbers can be done a number of ways. You can round a float up or down to the nearest integer or you could round to a specific precision. Even then you can choose whether or not to round halves up or down and even round towards even and odd values. Let’s take a look at the PHP code to pull this off:

Round up to the nearest integer

ceil(12.30); // 13

Round down to the nearest integer

floor(6.66); // 6

Round to 2 decimal places

round(3.1415926535, 2); // 3.14

Round half up

round(7.5, 0, PHP_ROUND_HALF_UP); // 8

Round half down

round(7.5, 0, PHP_ROUND_HALF_DOWN); // 7

Round half even

round(5.5, 0, PHP_ROUND_HALF_EVEN); // 6

Round half odd

round(5.5, 0, PHP_ROUND_HALF_ODD); // 5

As always, there’s many ways to skin this cat with PHP.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Born again Linux user. Founder of Holiday API, Backend Engineering Manager and Emoji Specialist at Mailshake (WE'RE HIRING!), and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Pears and Perils
Antifragile: Things That Gain from Disorder
Code Girls: The Untold Story of the American Women Code Breakers of World War II

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles