Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize integer remainder and return negative number by PHP

Shulou Source: shulou.com Published: 2022-06-03 15:47:19 10月03日 Update

This article mainly explains "PHP how to achieve integer remainder return negative", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "PHP how to achieve integer remainder return negative"!

Let's start with an example.

The copy code is as follows:

$res = 16244799483;

echo $res%9999999;

//The output result is-5069794, the correct result should be 4801107

In fact, this is a PHP bug. PHP is a weakly typed language. It's got a built-in machine to determine the type of user.

But machines are machines. There are times when judgment goes wrong. Just like above. So at this point we need manual intervention.

So I thought of the following method to solve PHP integer remainder return negative problem.

The copy code is as follows:

$res = floatval(16244799483);

var_dump($res % 9999999);

We see the result is still wrong-5069794.

But it's worth noting that the return is an int.

PHP integer remainder return negative number problem is handled in this way.

PHP remainder defaults to integer.

And when you define $res = 16244799483;

It's already overflowing. So I'm adding coercion. to float type.

But that's not enough. Because the modulo calculation of % is still for integers.

So we need a function fmod. for float.

So the final PHP integer remainder return negative solution is:

The copy code is as follows:

$res = floatval(16244799483);

var_dump(fmod($res,9999999));

This solves the PHP integer remainder problem.

At this point, I believe that everyone has a deeper understanding of "how to achieve integer remainder return negative" in PHP, so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Tags: Integers negative numbers code types machines results problems content methods or learning practical deeper not enough labor examples interests functions methods practicality Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Redmi OPPO Reno vpn Shulou Information