loading...

PHP Round Number Rounding Numbers in PHP with round()

morinoko profile image Felice Forby ・2 min read

I don’t know about you, but to me, these converted temperatures from my last post are a bit hard to read. Converting 400 degrees Fahrenheit shows up as 204 degrees Celsius and converting 200 degrees Celsius shows up as 392 degrees Fahrenheit. These numbers aren’t really easy to set on an oven and a bit hard for the mind to process at first glance. Let's fix this problem by rounding to the nearest five degrees using PHP’s round() function!

Rounding to the Nearest 5 degrees

PHP’s round() function takes a decimal number (a.k.a. floating point number) and rounds up or down. In its most simple and default form, it will round the decimal to the nearest whole number. For example, round(3.457) will give you the result 3.

If you want to keep some of those decimal points, you can add in a precision argument. The default is 0, so without a precision value, round() will simply round to the nearest whole number as mentioned above. If you wanted to round the previous example to a precision of 2 decimal points, you would write round(3.457, 2) instead, resulting in 3.46.

So the basic usage goes like this:

round(<number you want to round>, <precision/number of decimal points to round to>)

There is also a third argument you can use called the “mode” which will let you control the way the rounding works. For example, do you want the rounding to go towards or away from zero, or to the next even or odd number? Learn more about that in the PHP Manual.

Rounding to the Nearest 5 degrees

When it comes to oven temperatures, however, we don’t just want to round to the nearest whole number, we want to round to the nearest 5 degrees because these are more likely to be actual temperatures you can set your oven to and are much easier to read. But, if we just do something like round(204), the result is just going to be 204. How can we get this to round to the nearest 5 degrees?

Here’s the trick: First, divide the number you want to round by 5. Then round it. Last, multiply it by 5 again. This will give you the original number rounded to the nearest multiple of 5.

$celsius = round(204/5) * 5;
print $celsius;

// This will print "205"

If you wanted multiples of 10 instead, just take your number and divide by 10, round, and multiply by 10 again.

$celsius = round(204/10) * 10;
print $celsius;

// This will print "200"

Let’s see it in action with the temperature conversion list from my last post.

Converting Celsius to Fahrenheit and Rounding Results

Converting Fahrenheit to Celsius and Rounding Results

There we go! Pretty temperatures that you can actually input into your oven :)

Posted on Oct 28 '18 by:

morinoko profile

Felice Forby

@morinoko

I'm a former Japanese translator turned full-stack web engineer. I work mostly with Ruby and Rails, and love working on both the back-end and the front-end. I'm based in Japan :)

Discussion

markdown guide