Summarizing the considerations of numerical calculation in PHP _php tips

Source: Internet
Author: User

One: Rounding

1.round-the floating-point numbers

Float round (float $val [, int $precision])

2:floor-the method of rounding (rounding down)

Float Floor (float $value)

3.ceil-in one method (rounding up)

float ceil (float $value)

Pit point: When the value is an integer for example 11 floor (one) = ten, ceil (11) = 12; The problem is obvious, so be careful when calculating

Solution: Floor (11 + 0.01);

Two: integer and decimal multiplication apart

Pit Point:3.5 * 100 = 300, even if you are not good at math, in the PHP world This is the truth, if you use PHP's +-*/to calculate floating-point numbers, you may encounter some problems of computational error, such as Echo intval (0.58*100); Will print 57 instead of 58, which is actually a bug in the bottom of the computer that cannot accurately represent floating-point numbers, which is cross-language, and I've encountered this problem with Python. So basically most languages provide a class library or function library for accurate computing, such as PHP with a high accuracy function library of BC

Workaround: change the integer form to floating-point 3.5 * (float) 100 = 350

Three: The oddity of floating point numbers

Pit point:8.50–8 = 0.500000001 In fact, the reason is almost 2.

Solution: round the result () and improve the precision

Summarize

The above is the PHP data calculation of the full contents of the note, I hope this article in the content of PHP in the data calculation can be helpful.

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.