Google
 

Monday, December 10, 2007

Floor Basically Truncates

floor basically truncates, or chops off everything to the right of a decimal. For instance, if you have a length of 5.1234, but just wanted the whole number, you could use the following code:

<?php
$length = 5.1234; //this is our original length
$length = floor($length); //length is truncated, original variable name is kept
print "$length"; //this prints our result
?>

This code would print the following: 5

Now, although there is a specific function in PHP for rounding, rounding can also be performed with the floor function. Let's say we wanted to round the length to the hundredths place.

<?php
$length = 5.1234;
$length = floor(($length) * 100 + .5) * .01;
print "$length";
?>

The result is: 5.12

This works because, first, the length is multiplied by 100, which moves the decimal point to the right two places, giving us the value of 512.34. Next .5 is added to the length, which gives us a value of 512.84. Then the floor function truncates the value, leaving us with 512. Lastly, to compensate for multiplying by 100 earlier, now we must divide by 100, or in this case, multiply by .01. This moves the decimal point back 2 places to it's original place and gives us the rounded value of 5.12.

We can also round to other values, such as the thousandths, by adjusting the code as follows:

<?php
$length = 5.1234;
$length = floor(($length) * 1000 + .5) * .001;
print "$length";
?>

Result: 5.123
asp55 at digiclub dot org
14-Feb-2003 02:52
Just a quick example of how to use this method

The first is just used to determine whether a number is even or odd:

<?
if(($x - (2 * floor($x/2))) == 0) echo "even";
else echo "odd";
?>

The second is just to determine a person�s age by comparing their birthday with the current date and rounding down:

<? $age = floor((date(Ymd) - $bday)/10000); ?>