The relevant solution to return negative numbers of the PHP integer remainder _php tips

Source: Internet
Author: User

Although the PHP language is powerful, but does not mean that it has no shortcomings, in the process of writing code will encounter some headache problems. Below we will introduce you to the solution of PHP integer return negative numbers.

Let's look at an example first.

Copy Code code as follows:

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

In fact, this is also a bug in PHP. The main thing is that PHP is a weakly typed language. He built a machine to judge the type of user.

But the machine is a machine. There are also times when judgment goes wrong. It's like the top. So we need human intervention.

So I thought about using the following method to solve the problem that the PHP integer remainder returns a negative number.

Copy Code code as follows:

$res = Floatval (16244799483);
Var_dump ($res% 9999999);

We see the result is still -5069794 wrong.

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

Think about it in detail. The problem with PHP integer return of negative numbers is this.

PHP takes Yume to think of integers.

And when one defines $res = 16244799483;

It has already overflowed. So add the force type conversion. becomes a float type.

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

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

So ultimately the solution for the final PHP integer to return a negative number is:

Copy Code code as follows:

$res = Floatval (16244799483);
Var_dump (Fmod ($res, 9999999));

This solves the problem of the return of a negative number to the PHP integer fetch.:)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.