# floor

(PHP 4, PHP 5, PHP 7, PHP 8)

floor舍去法取整

### 说明

floor (float `\$value` ): float

`value`

### 范例

``` <?phpecho floor(4.3);   // 4echo floor(9.999); // 9echo floor(-3.14); // -4?> ```

### 参见

• ceil() - 进一法取整
• round() - 对浮点数进行四舍五入 add a note

### User Contributed Notes 18 notes

43
greene dot mc at removethispart dot gmail dot com
12 years ago
``` I believe this behavior of the floor function was intended.  Note that it says "the next lowest integer".  -1 is "higher" than -1.6.  As in, -1 is logically greater than -1.6.  To go lower the floor function would go to -2 which is logically less than -1.6.Floor isn't trying to give you the number closest to zero, it's giving you the lowest bounding integer of a float.In reply to Glen who commented: Glen01-Dec-2007 04:22<?php  echo floor(1.6);  // will output "1"  echo floor(-1.6); // will output "-2"?>instead use intval (seems to work v5.1.6):<?php  echo intval(1.6);  // will output "1"  echo intval(-1.6); // will output "-1"?> ```
41
seppili_ at gmx dot de
10 years ago
``` I use this function to floor with decimals:<?phpfunction floordec(\$zahl,\$decimals=2){         return floor(\$zahl*pow(10,\$decimals))/pow(10,\$decimals);}?> ```
11
maikl
6 years ago
``` A correction to the funcion floor_dec from the user "php is the best".If the number is 0.05999 it returns 0.59 because the zero at left position is deleted.I just added a '1' and after the floor or ceil call remove with a substr.Hope it helps.function floor_dec(\$number,\$precision = 2,\$separator = '.') {  \$numberpart=explode(\$separator,\$number);  \$numberpart=substr_replace(\$numberpart,\$separator,\$precision,0);  if(\$numberpart>=0) {    \$numberpart=substr(floor('1'.\$numberpart),1);  } else {    \$numberpart=substr(ceil('1'.\$numberpart),1);  }  \$ceil_number= array(\$numberpart,\$numberpart);  return implode(\$separator,\$ceil_number);} ```
Antonio
1 year ago
``` <?phpecho (2.3 * 100) . ' - ' . round(2.3 * 100, 0) .  ' - ' . floor(2.3 * 100);?>.Result:230 - 230 - 229Be careful! ```
12
benrr101 at gmail dot com
12 years ago
``` But, if you want the number closest to zero, you could use this:<?php  if(\$foo > 0) {    floor(\$foo);  } else {    ceil(\$foo);  }?>-benrr101 ```
11
fragov at gmail dot com
12 years ago
``` Have solved a "price problem": <?php \$peny = floor(\$row->price*1000) - floor(\$row->price)*1000)/10; ?> ```
Glen
13 years ago
``` <?php  echo floor(1.6);  // will output "1"  echo floor(-1.6); // will output "-2"?>instead use intval (seems to work v5.1.6):<?php  echo intval(1.6);  // will output "1"  echo intval(-1.6); // will output "-1"?> ```
Leon Grdic
5 years ago
``` Warning: do not use Seppili's function to floor with decimals. It will lead you to a lot of trouble because of float number precision.For example floordec(0.29, 2) will result in 0.28.Here's a little fix that will help you get around some problems:<?phpfunction floordec(\$value,\$decimals=2){        return floor(\$value*pow(10,\$decimals)+0.5)/pow(10,\$decimals);}?> ```
jay at w3prodigy dot com
12 years ago
``` Note: <?php \$int = 0.99999999999999999; echo floor(\$int); // returns 1 ?> and <?php \$int = 0.9999999999999999; echo floor(\$int); // returns 0 ?> ```
jolyon at mways dot co dot uk
16 years ago
``` Beware of FLOAT weirdness! Floats have a mind of their own, and what may look like an integer stored in a float isn't. Here's a baffling example of how floor can be tripped up by this: <?php \$price = 79.99; print \$price."\r\n";     // correct result, 79.99 shown \$price = \$price * 100; print \$price."\r\n";    // correct result, 7999 shown print floor(\$price);    // 7998 shown! what's going on? ?> The thing to remember here is that the way a float stores a value makes it very easy for these kind of things to happen. When the 79.99 was multiplied by 100, the actual value stored in the float was probably something like 7998.9999999999999999999999999999999999, PHP would print out 7999 when the value is displayed but floor would therefore round this down to 7998. THe moral of this story - never use float for anything that needs to be accurate! If you're doing prices for products or a shopping cart, then always use an integer and store prices as a number of pence, you'll thank me for this later :) ```
Anonymous
18 years ago
``` mathematical functions lack a floating point version of the modulo operation, which returns the difference between the floor() of the argument and the argument itself: <?php function fmod(\$value) {   return \$value - floor(\$value); } ?> Very useful with trigonometric functions to reduce the angle argument to a circle that includes angle 0. Useful also to reduce an arbitrarily large floating point value into an entropy source, by first transforming this value into a pair using logarithm functions with distinct bases (add 1 if the function can return 0, to avoid floating point errors with logarithms!): <?php \$f = 1 + @disk_free_space("/tmp"); \$r = (int)(fmod(Log(\$f)) * 0x7FFFFFFF) ^ (int)(fmod(Log10(\$f)) * 0x7FFFFFFF) ?> Then \$r can be used as a good entropy source, if the free space in your temporary folder used by PHP is constantly evolving within a large range of values. You can combine this value by xoring it with other values such as time(), (int)microtime(), ip2long(\$_SERVER['REMOTE_ADDR'], \$_SERVER['REMOTE_PORT'], getmypid(), ... ```
-3
lewis at lewishenshall dot co dot uk
11 years ago
``` If you're wanting to round down to the nearest hundred:<?phpfunction rounddowntohundred(\$theNumber) {    if (strlen(\$theNumber)<3) {    \$theNumber=\$theNumber;    } else {    \$theNumber=substr(\$theNumber, 0, strlen(\$theNumber)-2) . "00";    }    return \$theNumber;}?> ```
-10
php is the best
8 years ago
``` Floor decimal numebrs with precision:function floor_dec(\$number,\$precision,\$separator){    \$numberpart=explode(\$separator,\$number);    \$numberpart=substr_replace(\$numberpart,\$separator,\$precision,0);    if(\$numberpart>=0)    {\$numberpart=floor(\$numberpart);}    else    {\$numberpart=ceil(\$numberpart);}     \$ceil_number= array(\$numberpart,\$numberpart);    return implode(\$separator,\$ceil_number);}echo floor_dec(1.125,2,"."); //1.12echo floor_dec(-1.3436,3,"."); //-1.344echo floor_dec(102938.1,4,"."); //102938.1 ```
-9
illyena at musefish dot net
16 years ago
``` For calculating the number of days, hours, minutes and seconds to an event. <?php \$then = date(mktime(8,0,0,6,25,2004)); //remember that mktime is hour,min,sec,month,day,year \$now = date("U"); // "U" is the number of seconds since the epoch, equivilant to using "YmdHis" \$time = \$then - \$now; //gets the number of seconds between now and the event \$days = floor(\$time/86400); //rounds down to the whole number, in this case # of days echo \$days." Days"; \$time = \$time - (\$days*86400); //leaves you with the amount of time ramaining after subtracting the days \$hours = floor(\$time/3600); //rounds down to the whole number, in this case # of hours echo \$hours." Hours"; \$time = \$time - (\$hours*3600); //leaves you with the amount of time ramaining after subtracting the hours \$min = floor(\$time/60); //rounds down to the whole number, in this case # of minutes echo \$min." Minutes"; \$sec = \$time - (\$min*60); //leaves you with the amount of time ramaining after subtracting the minutes which is equivilant to the remainins seconds echo \$sec." Seconds"; ?> ```
-9
till at tonda dot de
6 years ago
``` Note that the use of floor may (intended or not) uncover false integers:<?php\$arrRoots=array();\$arrRoots[]=pow(27,(1/3));        // pow(3,3)=27\$arrRoots[]=pow(64,(1/3));        // pow(4,3)=64for(\$i=0;\$i<count(\$arrRoots);\$i++){if(\$arrRoots[\$i]!=floor(\$arrRoots[\$i]))  echo '<div style="background-color:#ffff99">';echo 'Unfloored value: '.\$arrRoots[\$i].' (Format float? '.is_float(\$arrRoots[\$i]).')<br />';echo 'Floored value: '.floor(\$arrRoots[\$i]).' (Format float? '.is_float(floor(\$arrRoots[\$i])).')';if(\$arrRoots[\$i]!=floor(\$arrRoots[\$i]))  echo '</div>';echo '<br /><br />';}?>The directly retrieved cubic root of 64 (by pow with a fraction exp) equals 4; an outcome any maths teacher will reckon correct.Yet bringing the same number - the cubic root of 64 retrieved in the very same manner - to the floor will result in a value of 3 only. This behaviour is in no way exceptional.It is pivotal to check whether you are dealing with genuine integers or floats in disguise. floor should be used carefully. ```
-6
itbudaoweng at gmail dot com
2 years ago
``` If you want to ceil decimal, DO NOT USEfunction floordec(\$zahl,\$decimals=2){         return floor(\$zahl*pow(10,\$decimals))/pow(10,\$decimals);}if you call it floordec(0.58, 2) it return 0.57.[USE below instead,both work fun]/** * * @param \$money_yuan * @param int \$scale * @return string */static function floor(\$money_yuan, \$scale=2) {     return bcsub(\$money_yuan, "-", 0, \$scale);}/** * @param \$money_yuan * @param int \$scale * @return string */static function floor2(\$money_yuan, \$scale = 2) {          return substr(sprintf("%.".(++\$scale)."f", \$money_yuan), 0, -1);} ```
-11
josoort at home dot nl
6 years ago
``` You can simply make a floor with decimals function by using the round() function and subtract 0.05 to the value if the value must have 1 decimal accuracy, or 0.005 for 2 decimals accuracy, or 0.0005 for 3 decimals etc.Example :function floorDec(\$input, \$decimals){    return round(\$input - (5 / pow(10, \$decimals + 1)), \$decimals);} ```
-32
PHP Helper
17 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 keptprint "\$length"; //this prints our result?>This code would print the following: 5Now, 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.12This 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 ```
{"ft_lang_label":"__label__en","ft_lang_prob":0.8965534,"math_prob":0.9865662,"size":1292,"snap":"2021-04-2021-17","text_gpt3_token_len":349,"char_repetition_ratio":0.14285715,"word_repetition_ratio":0.044247787,"special_character_ratio":0.31656346,"punctuation_ratio":0.21180555,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9908373,"pos_list":[0,1,2,3,4],"im_url_duplicate_count":[null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-01-18T04:47:05Z\",\"WARC-Record-ID\":\"<urn:uuid:9dc5d712-2ddb-4b81-b7e6-48d7d61b977e>\",\"Content-Length\":\"71678\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:86ba126c-f86e-4c59-b006-05a312ef8638>\",\"WARC-Concurrent-To\":\"<urn:uuid:f10edb6c-8f1b-4a4c-a5d2-b469e5869b93>\",\"WARC-IP-Address\":\"39.104.110.223\",\"WARC-Target-URI\":\"http://php.p2hp.com/manual/zh/function.floor.php\",\"WARC-Payload-Digest\":\"sha1:R2PXKTBUJWPQIRDE3W4PNMEGSZJDBBJ3\",\"WARC-Block-Digest\":\"sha1:ZPP2ZHT4G6ALHPYGZKRKQZGTFLN7WAPT\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-04/CC-MAIN-2021-04_segments_1610703514121.8_warc_CC-MAIN-20210118030549-20210118060549-00131.warc.gz\"}"}