Statement on glibc/iconv Vulnerability

Voting

: min(nine, zero)?
(Example: nine)

The Note You're Voting On

PHP Helper
20 years ago
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

<< Back to user notes page

To Top