


Parse PHP to handle floating point numbers, precision operations, number processing, etc.
This article will introduce you to PHP's processing of floating point numbers, precision operations, number processing, etc. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Preface
1. PHP floating point type numbers are used for calculations. If you are not careful, deviations will occur, especially in the financial industry, electronic merchant orders, and shopping mall projects.
2. Floating point numbers have limited precision. Although it depends on the system, PHP usually uses the IEEE 754 double format, so the maximum relative error due to rounding is 1.11e-16. Non-basic mathematical operations may give larger errors, and error propagation when doing compound operations needs to be taken into account. Never trust a floating-point result to the last digit, and never compare two floating-point numbers for equality. If you really need higher precision, you should use arbitrary precision math functions or the gmp function.
1. Operation
Error
//加 $a = 0.1; $b = 0.7; $c = intval(($a + $b) * 10); echo $c."<br>"; //输出:7 //减 $a = 100; $b = 99.98; $c = $a - $b; echo $c."<br>"; //输出:0.019999999999996 //乘 $a = 0.58; $b = 100; $c = intval($a * $b); echo $c."<br>"; //输出:57 //除 $a = 0.7; $b = 0.1; $c = intval($a / $b); echo $c."<br>"; //输出:6
Correct
1. For arbitrary-precision mathematics, PHP provides support for binary arithmetic on numbers of any size and precision represented as strings.
2. Official manual: php.net/manual/zh/book.bc.php
3. Before using it, please confirm whether bcmath has been installed.
//加 $a = 0.1; $b = 0.7; $c = intval(bcadd($a, $b, 1) * 10); echo $c."<br>"; //输出:8 //减 $a = 100; $b = 99.98; $c = bcsub($a, $b, 2); echo $c."<br>"; //输出:0.02 //乘 $a = 0.58; $b = 100; $c = intval(bcmul($a, $b)); echo $c."<br>"; //输出:58 //除 $a = 0.7; $b = 0.1; $c = intval(bcp($a, $b)); echo $c."<br>"; //输出:7
In addition to addition, subtraction, multiplication and division, bcmath also provides the following methods:
1. bccomp compares two arbitrary precision numbers
2. bcmod compares an arbitrary Precision number modulus
3. bcpow The power of any precision number
4. bcpowmod The modulus of the power of a high-precision number
5. bcscale Sets the default decimal point retention digits for all BC math functions
6. bcsqrt The quadratic root of an arbitrary precision number
2. Commonly used numerical processing solutions
Rounding by rounding (rounding down)
echo floor(5.1); //输出:5 echo floor(8.8); //输出:8
Rounding method (rounding up)
echo ceil(5.1); //输出:6 echo ceil(8.8); //输出:9
Ordinary rounding method
echo round(5.1); //输出:5 echo round(8.8); //输出:9 //保留两位小数并且进行四舍五入 echo round(5.123, 2); //输出:5.12 echo round(8.888, 2); //输出:8.89 //保留两位小数并且不进行四舍五入 echo substr(round(5.12345, 3), 0, -1); //输出:5.12 echo substr(round(8.88888, 3), 0, -1); //输出:8.88
Banker's rounding method
1. Rounding Consider five, if the last five is not empty, then add one. If the last five is empty, look at the odd or even number. If the first five are even, then discard it. If the first five are odd, then add one.
2. Keep two decimal places. Example:
1.2849 = 1.28 -> 四舍 1.2866 = 1.29 -> 六入 1.2851 = 1.29 -> 五后非空就进一 1.2850 = 1.28 -> 五后为空看奇偶,五前为偶应舍去 1.2750 = 1.28 -> 五后为空看奇偶,五前为奇要进一
Numeric formatting (thousands grouping)
1. Applied to the display of amounts, such as bank card balances that we often see.
echo number_format('10000.98', 2, '.', ','); //输出:10,000.98 echo number_format('340888999', 2, '.', ','); //输出:340,888,999.00
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Parse PHP to handle floating point numbers, precision operations, number processing, etc.. For more information, please follow other related articles on the PHP Chinese website!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
