PHP floating point calculation comparison and inaccurate solutions to rounding, inaccurate rounding_PHP tutorial

WBOY
Release: 2016-07-13 09:45:34
Original
975 people have browsed it

Solution to inaccurate floating-point calculation comparison and rounding in PHP. Inaccurate rounding

An interesting phenomenon in PHP that should be seen in many programming languages. This is due to the problem of the computer’s own recognition of floating point numbers....

[php] view plaincopy ​
  1. $f = 0.58;
  2. var_dump(intval($f * 100 *100)); //result 5799
  3. var_dump((float)($f * 100 *100)); //result 5800
  4. echo (int)((0.1 0.7)*10); //Result 7
  5. echo (float)((0.1 0.7)*10); //Result 8

[php] view plaincopy ​
  1. $a = 0.1;
  2. $b = 0.7;
  3. var_dump(($a $b) == 0.8);
  4. //The printed value is actually boolean false
[php] view plaincopy ​
  1. $a = 0.1;
  2. $b = 0.7;
  3. var_dump(bcadd($a,$b,2) == 0.8);// bool true

When calculating floating point numbers, remember not to convert floating point numbers into integers, otherwise unpredictable errors will occur.

So never trust that a floating point number result is accurate to the last digit, and never compare two floating point numbers to see if they are equal.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1040163.htmlTechArticlePHP floating point calculation comparison and inaccurate rounding solution, inaccurate php interesting phenomenon should be Many programming languages ​​have this phenomenon. This is because of the computer itself...
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