00 Votes

PHP: Only MOD-Operator? How to do DIV in PHP?

Question by Guest | 2014-03-04 at 06:42

Up to now, in PHP, I only know the Modulo-Operator % to get the rest of a division (12 % 10 = 2). In other programming languages, this operator is usually called MOD.

However, in other programming languages there is also a DIV-Operator available returning the integer before the decimal point. This operator is just cutting off the fractional digits (12 DIV 10 = 1).

In PHP, I have not found this operator yet. Is there one?

ReplyPositiveNegativeDateVotes
0Best Answer0 Votes

As far as I know, in PHP there is no explicit DIV-Operator available which you can easily write as one character in code like %. Instead, you can use the function floor():

$a = floor(12/10);
echo $a; // 1

The PHP function floor() crops the digits behind the decimal point. 12 divided by 10 are 1.2 - with cutting off the places behind the decimal point the 1 remains - and this is the integer before the decimal point that you wanted.

You can get similar results by rounding a number in PHP.
2014-03-05 at 12:00

ReplyPositive Negative
00 Votes

You could also use the PHP function bcdiv for your purpose.

This function takes three parameters:

  1. Left operand as string
  2. Right operand as string
  3. Number of decimal places for the result

To reflect the conventional DIV, you can write:

echo bcdiv('12', '10', 0);  // 1
echo bcdiv('12', '10', 2);  // 1.20

So, for bcdiv('12', '10', 0), the function is behaving like the DIV operator. If you are passing another value instead of 0 as a third parameter, another number of outputted decimal places can be triggered.
2014-04-24 at 16:36

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.