note 38423 added to function.floor
| From: | PHPHelper at rn2 dot php dot net | Date: | Sat, 20 Dec 2003 07:39:50 +0000 |
| Subject: | note 38423 added to function.floor | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-62261@lists.php.net to get a copy of this message | ||
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
----
Manual Page -- http://www.php.net/manual/en/function.floor.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+38423
Delete -- http://master.php.net/manage/user-notes.php?action=delete+38423&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+38423&report=yes
Search -- http://master.php.net/manage/user-notes.php