Home > Backend Development > PHP Tutorial > Related solutions to PHP integer remainder returning negative numbers_PHP Tutorial

Related solutions to PHP integer remainder returning negative numbers_PHP Tutorial

WBOY
Release: 2016-07-13 10:29:47
Original
897 people have browsed it

Although the PHP language is powerful, it does not mean that it has no shortcomings. In the process of writing code, you will inevitably encounter some headaches. Below we will introduce to you the solution to the PHP integer remainder return negative number.

Let’s look at an example first.

Copy code The code is as follows:

$res = 16244799483;
echo $res%9999999;
/ / The output result is -5069794, the correct result should be 4801107

In fact, this can be considered a BUG in PHP. The most important thing is that PHP is a weakly typed language. It has a built-in machine to determine the user type.

But a machine is a machine after all. There are times when judgments are wrong. Just like the above. So at this time we need manual intervention.

So I thought of using the following method to solve the problem of PHP integer remainder returning a negative number.

Copy code The code is as follows:

$res = floatval(16244799483);
var_dump($res % 9999999) ;

We see that the result is still wrong - 5069794.

But it is worth noting that the return is an int type.

Think about it in detail. The problem of PHP integer remainder returning a negative number is handled like this.

PHP remainder is an integer by default.

And when you define $res = 16244799483;

In fact, it has already overflowed. So we need to add forced type conversion. It becomes a float type.

But this is not enough. Because the modulo calculation of % is still based on integers.

So we need a function fmod. It is for float type.

So the final solution to PHP integer remainder returning a negative number is:

Copy code The code is as follows:

$res = floatval(16244799483);
var_dump(fmod($res, 9999999));

In this way we solve the problem of PHP integer remainder returning a negative number.:)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/770578.htmlTechArticleAlthough the PHP language is powerful, it does not mean that it does not have shortcomings. You will inevitably encounter it in the process of writing code. Some headaches. Below we will introduce to you about PHP integer retrieval...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template