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:
$num = 123456789;
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.
0 comments:
Post a Comment