I have previously talked about rounding numbers in PHP, but what if you wanted to round the number to the nearest thousand?
It is possible to do this with the native round() function in PHP by using a negative number as the second parameter. The round() function has two parameters, the first is the number to be rounded and the second is the number of places to round the number to, also known as the precision. The default for round() is to round the number to the nearest whole number, by using positive numbers as the second parameter you can set the number of decimal places to round the number to. Giving a negative number as the second parameter will allow you to round the number to the nearest full number. For example, to round a number to the nearest thousand you can put -3 as the precision, this will change the number 12,345 into 12000.
Here is a full example:
1 2 3 4 5 6 7 8 9 10 11 12
$num = 123456789; echo round($num,0); // whole number - prints 123456789 echo round($num,-1); // ten - prints 123456790 echo round($num,-2); // hundred - prints 123456800 echo round($num,-3); // thousand - prints 123457000 echo round($num,-4); // ten thousand - prints 123460000 echo round($num,-5); // hundered thousand - prints 123500000 echo round($num,-6); // million - prints 123000000 echo round($num,-7); // ten million - prints 120000000 echo round($num,-8); // hundred million - prints 100000000 echo round($num,-9); // billion - prints 0
Note that if you set the precision to be more than the actual number present then you with either get the next highest number or zero. For example, when rounding the number 15, if the precision is -1 then the result is 20 as this is the nearest full ten. However, if -2 is used then the result is 0 as this is the nearest full hundred.
This can cause errors if you are rounding lots of different sized values, so a neat little trick is to use the strlen() function to find out how many characters are in a number and then round to the nearest largest number. You can take the number of characters, subtract 1 to make it one less than the length of the string or you will round some numbers down to zero. You then multiply this value by -1 to invert it.