除以整数并得到整数值

在 C 或 Python 这样的语言中,如果我把一个整数除以一个整数,我得到的是一个整数:

>>> 8/3
2

但是在 PHP 中,如果我用 /将一个整数除以另一个整数,有时会得到一个浮点数:

php > var_dump(6/3);
int(2)
php > var_dump(8/3);
float(2.6666666666667)

我想用 Python 或者 C 来做除法,所以8/3等于2。我如何在 PHP 中做到这一点?

109102 次浏览

use round() function to get integer rounded value.

round(8 / 3); // 3

or

Use floor() function to get integer value

floor(8 / 3); // 2

Update:

We can also use intdiv built-in function to get integer value from PHP v7

intdiv(8,3); // 2

There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.


var_dump(25/7);           // float(3.5714285714286)
var_dump((int) (25/7));   // int(3)
var_dump(round(25/7));    // float(4)

PhP manual

use this....

intval(1700000 / 300000 )...

this returns the integer value.

(int)(1700000 / 300000);

use type casting.

In PHP 7, there is intdiv function doing exactly what you want.

Usage:

intdiv(8, 3);

Returns 2.

You can use the shortform by adding |0 to the end

8/3|0

There are several ways to perform integer division in PHP. The language doesn't have an operator for integer division, but there are several options for rounding the floating point quotient to an integer:

<?php
$pos = 1;
$neg = -1;
$divisor = 2;


// No rounding (float division)
var_dump($pos / $divisor);          //  0.5 (float)
var_dump($neg / $divisor);          // -0.5 (float)


// Round toward zero (like C integer division)
var_dump((int)($pos / $divisor));   //  0 (int)
var_dump((int)($neg / $divisor));   //  0 (int)


// Round half away from zero
var_dump(round($pos / $divisor));   //  1 (float)
var_dump(round($neg / $divisor));   // -1 (float)


// Round down
var_dump(floor($pos / $divisor));   //  0 (float)
var_dump(floor($neg / $divisor));   // -1 (float)


# And on PHP 7 you can round toward zero with intdiv():
var_dump(intdiv($pos, $divisor));   //  0 (int)
var_dump(intdiv($neg, $divisor));   //  0 (int)  Rounded toward zero

On PHP 7 you can use intdiv($p, $q) to directly perform integer division. This is equivalent to (int)($p / $q) on PHP 5.

For PHP version 7 => intdiv(a,b)

And for versions less than 7 (like 5.6) => (int)floor(abs(a/b))

FOR PHP 7 try intdiv() Function:

Syntax: int intdiv($dividend, $divisor)

          <?php
$dividend = 19;
$divisor = 3;
echo intdiv($dividend, $divisor);
?>

For Older versions of PHP:

         <?php
// Convert $total_minutes to hours and minutes.


$total_minutes = 640;
$minutes = $total_minutes % 60;
$hours = ($total_minutes - $minutes) / 60;


echo "Time taken was $hours hours $minutes minutes";
?>