Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round up a number to nearest 10?

Tags:

php

rounding

How can we round off a number to the nearest 10 in php?

Say I have 23, what code would I use to round it off to 30?

like image 617
tarnfeld Avatar asked Oct 24 '09 21:10

tarnfeld


People also ask

How do you round a number to the nearest 10?

If the number you are rounding is followed by 5, 6, 7, 8, or 9, round the number up. Example: 38 rounded to the nearest ten is 40. If the number you are rounding is followed by 0, 1, 2, 3, or 4, round the number down. Example: 33 rounded to the nearest ten is 30.

What is 999 rounded to the nearest 10?

999 is between 990 and 1,000 and rounded to the nearest 10 is 1,000 .


1 Answers

floor() will go down.

ceil() will go up.

round() will go to nearest by default.

Divide by 10, do the ceil, then multiply by 10 to reduce the significant digits.

$number = ceil($input / 10) * 10; 

Edit: I've been doing it this way for so long.. but TallGreenTree's answer is cleaner.

like image 115
Daren Schwenke Avatar answered Sep 20 '22 13:09

Daren Schwenke