Code analysis of decimal precision in php

不言
Release: 2023-04-03 15:44:02
Original
2002 people have browsed it

The content of this article is about the code analysis of decimal precision in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Encountered precision issues when rounding to two decimal places in the project:

$num = 0.99;
$num1 = round($num, 2);//0.98999999999999999
$num2 = floatval($num);//0.98999999999999999
Copy after login

Current solution:

sprintf("%.2f", round($money, 2));//会自动四舍五入
echo substr(sprintf("%.3f",$n), 0, -1);//不四舍五入
Copy after login

Test results:

var_dump(json_encode(round(0.99 ,2)));//0.98999999999999999
var_dump(round(0.99 ,2));//0.99

$f = 0.58;    
var_dump(intval($f * 100));//57
Copy after login

About equal to 57 We can analyze the problem:

Representation of floating point numbers (IEEE 754: IEEE Binary Floating Point Arithmetic Standard):

Floating point numbers, taking 64-bit length (double precision) as an example , will be represented by 1 sign bit (E), 11 exponent bits (Q), and 52 mantissas (M) (a total of 64 bits).

Sign bit: The highest bit indicates the sign of the data, 0 indicates Positive number, 1 means negative number.

Exponent bit: represents the power of the data with base 2, the exponent is represented by offset code

Mantissa: represents the valid digits after the decimal point of the data.

0.58 For binary representation For example, it is an infinitely long value:

The binary representation of 0.58 is basically (52 bits): 0010100011110101110000101000111101011100001010001111

The binary representation of 0.57 (52 bits) is basically: 001000 111101011100001010001111010111000010100011110

The binary numbers of the two, if calculated only through these 52 bits, are:

0.58 --> 0.5799999999999996

0.57 --> 0.5699999999999999

So, the result of 0.58 * 100 will be: 57.999999999, converted to integer type: 57

Regarding the binary representation of floating point numbers, you can refer to: Binary representation of floating point numbers

Similar to:

(0.1 + 0.7) == 0.8//false

floor((0.1+0.7)*10)//7 
//内部结果可能是:7.9999999999
//所以:不可能精确的用有限位数表达某些十进制分数
1/3=3.33333333333
//而3.333333333333333*3,却不是1
Copy after login

So conclusion:

So never believe that the floating point number result is accurate to the last digit, and never compare whether two floating point numbers are equal. If you really need higher precision, you should use arbitrary precision mathematical functions or gmp functions

It is recommended to use high-precision functions:

High-precision functions

  • bcadd — Addition of 2 arbitrary-precision numbers

  • bccomp — Compare two arbitrary-precision numbers

  • bcp — Calculate the division of two arbitrary-precision numbers

  • bcmod — Modulo an arbitrary-precision number

  • bcmul — Multiplication calculation of 2 arbitrary precision numbers

  • bcpow — Power of an arbitrary precision number

  • ##bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus

  • bcscale — Set the default number of decimal places for all bc math functions

  • bcsqrt — The square root of an arbitrary-precision number

  • bcsub — The subtraction of two arbitrary-precision numbers

Use high-precision functions to achieve rounding:

    function getBcRound($number, $precision = 0)
    {
        $precision = ($precision < 0)
                   ? 0
                   : (int) $precision;
        if (strcmp(bcadd($number, &#39;0&#39;, $precision), bcadd($number, &#39;0&#39;, $precision+1)) == 0) {
            return bcadd($number, &#39;0&#39;, $precision);
        }
        if (getBcPresion($number) - $precision > 1) {
            $number = getBcRound($number, $precision + 1);
        }
        $t = &#39;0.&#39; . str_repeat(&#39;0&#39;, $precision) . &#39;5&#39;;
        return $number < 0
               ? bcsub($number, $t, $precision)
               : bcadd($number, $t, $precision);
    }
    
    function getBcPresion($number) {
        $dotPosition = strpos($number, &#39;.&#39;);
        if ($dotPosition === false) {
            return 0;
        }
        return strlen($number) - strpos($number, &#39;.&#39;) - 1;
    }
    
    $money = getBcRound(0.99, 2);
Copy after login
Recommended related articles:

Parsing of AES encrypted files in PHP (with code)

Request codes for post mode and get mode in curl of php

About content analysis of PHP intermediate keys

The above is the detailed content of Code analysis of decimal precision in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template