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
WBOYOriginal
2016-07-15 13:32:25748browse

Let’s look at an example first.

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

In fact, this is also 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's 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 PHP integer remainder The problem of returning negative numbers.

$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 defaults to an integer .

And when you define $res = 16244799483;

, it actually overflows. So you need to add forced type conversion. It becomes a float type.

But like this It’s not enough. Because the modulo calculation of % is still for integers.

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

So in the end, the solution to PHP integer remainder return negative number For:

$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/446135.htmlTechArticleLet’s take a look at an example first. $res = 16244799483; echo $res%9999999; // The output result is - 5069794, the correct result should be 4801107. In fact, this is also considered a BUG in PHP. The main thing is that PHP is...
Statement:
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