php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #41802 Float values are implicitly converted to int when using modulo operator
Submitted: 2007-06-25 14:18 UTC Modified: 2007-08-16 13:31 UTC
From: cosborne83 at hotmail dot com Assigned:
Status: Closed Package: Documentation problem
PHP Version: 5.2.3 OS: Windows XP
Private report: No CVE-ID: None
 [2007-06-25 14:18 UTC] cosborne83 at hotmail dot com
Description:
------------
When applying the % (modulo) operator to floats, the values are implicitly converted to int, which causes problems in many instances.

This means that you can't use floats to store integer values larger than the maximum int value if you wish to perform modulo operations.

Theis behaviour is also invalid since modulo is well defined on floats as well as ints.

Reproduce code:
---------------
$m = 5000000000;
$n = 3.5;
// Integer modulo but with large int stored as float
print $m % 10;
print "\n";
// Non-integer modulo.
print $n % 1.5;

Expected result:
----------------
0
0.5

Actual result:
--------------
4
0

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-06-25 14:35 UTC] tony2001@php.net
This is how it works in C, hence this is how it should work in PHP.
Reclassified as docu problem.
 [2007-08-16 13:31 UTC] vrana@php.net
This bug has been fixed in the documentation's XML sources. Since the
online and downloadable versions of the documentation need some time
to get updated, we would like to ask you to be a bit patient.

Thank you for the report, and for helping us make our documentation better.

"Operands of modulus are converted to integers (by stripping the decimal part) before processing. "
 [2011-04-18 16:48 UTC] php at richardneill dot org
I think this warning needs to be much stronger - especially because % is grouped with 4 other operators (*+-/) that do behave correctly with floats. I'd suggest using a WARNING box to say:

"Operands of modulus are cast to int before processing. This means that values exceeding PHP_INT_MAX will give the wrong result, EVEN when the operand is has an exact integer representation in floating-point format. For example, '0xffffffff %2' will evaluate to -1"

Imho the behaviour is also wrong, because PHP normally does integer overflow (which is good), but % uses integer wraparound (bad).
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Fri Jul 04 10:01:34 2025 UTC