Table of Contents
The solution to inaccurate floating point calculation comparison and rounding in PHP, inaccurate rounding
Home Backend Development PHP Tutorial Solutions to inaccurate floating point calculation comparison and rounding in PHP, inaccurate rounding_PHP Tutorial

Solutions to inaccurate floating point calculation comparison and rounding in PHP, inaccurate rounding_PHP Tutorial

Jul 13, 2016 am 10:10 AM
Rounding floating point number Scientific notation

The solution to inaccurate floating point calculation comparison and rounding in PHP, inaccurate rounding

Comparison of floating point calculation results
An example of floating point calculation is as follows:

Copy code The code is as follows:

$a = 0.2+0.7;
$b = 0.9;
var_dump($a == $b);

The printed result is: bool(false). In other words, the calculation result of 0.2+0.7 here is not equal to 0.9, which is obviously against our common sense.

Regarding this issue, the official PHP manual once stated: Apparently a simple decimal fraction such as 0.2 cannot be converted to an internal binary format without losing a little precision. This has to do with the fact that it is impossible to express certain decimal fractions exactly with a finite number of digits. For example, 1/3 in decimal becomes 0.3333333….

We print the above variables in double precision format:

Copy code The code is as follows:

$a = 0.2+0.7;
$b = 0.9;
printf("%0.20f", $a);
echo '
';
printf("%0.20f", $b);

The output results are as follows:

Copy code The code is as follows:

0.89999999999999991118
0.90000000000000002220

Obviously here, as floating-point data, part of its accuracy has been lost and cannot reach complete accuracy. So never trust that a floating-point number result is accurate to the last digit, and never compare two floating-point numbers for equality. It should be noted that this is not a problem with PHP, but a problem with the computer's internal processing of floating point numbers! The same problem will be encountered in languages ​​such as C and JAVA.

So to compare two floating point numbers, we need to control them within the precision range we need before comparing, so use the bcadd() function to add the floating point numbers and convert the precision (to a string):

Copy code The code is as follows:

var_dump(bcadd(0.2,0.7,1) == 0.9); // Output: bool(true)

Floating point number rounding

In the article "PHP Rounding Functions Ceil and Floor", there is an example:

Copy code The code is as follows:

echo ceil(2.1/0.7); // Output: 4
?>

After the above discussion on floating-point number calculations, we know that this is caused by the inaccurate floating-point number calculation results:

Copy code The code is as follows:

printf("%0.20f", (2.1/0.7)); // Output: 3.00000000000000044409
?>

After the above discussion on floating point number calculation, we know that this is caused by the inaccurate floating point number calculation result, so we can use the round() function to deal with it:

Copy code The code is as follows:

echo ceil( round((2.1/0.7),1) );
?>

Although the round() function rounds according to the specified precision, retaining one decimal place has no effect on our rounding result.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/940487.htmlTechArticleComparison of floating point number calculations in PHP and solutions to inaccurate rounding, comparison of inaccurate floating point number calculation results with rounding An example of floating point calculation is as follows: Copy the code as follows: $a = 0.2+...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to convert string to decimal in php How to convert string to decimal in php Mar 22, 2023 pm 03:22 PM

PHP is a powerful programming language that is widely used in the field of web development. One of the very common situations is the need to convert a string to a decimal. This is very useful when doing data processing. In this article, we will explain how to convert string to decimal in PHP.

PHP floating point number rounding method PHP floating point number rounding method Mar 21, 2024 am 09:21 AM

This article will explain in detail the PHP floating point number rounding method. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Floating Point Rounding Overview Floating point numbers are represented in computers as a decimal point followed by an exponent, however, they are often stored in approximations with a limited number of digits. When you need to round a floating point number to a specific precision, there are several ways to do it. Method 1. round() function The round() function rounds a floating point number to the nearest integer. It accepts floating point numbers and optional precision parameters. For example: $num=1.55;echoround($num);//Output: 2echoround($num,1)

How to divide and round in php How to divide and round in php Mar 21, 2023 pm 02:52 PM

With the development of computer programming, we may encounter scenarios in which we need to perform division operations and rounding in our daily programming work. In PHP programming, we can use different methods to achieve this purpose.

Causes and avoidance strategies of PHP floating point calculation errors Causes and avoidance strategies of PHP floating point calculation errors Feb 27, 2024 pm 06:33 PM

As a popular server-side scripting language, PHP often encounters problems of loss of precision or calculation errors when performing floating-point calculations. These problems may affect the accuracy and stability of the program. This article will explore the causes of PHP floating point calculation errors, propose some avoidance strategies, and give specific code examples for reference. 1. Reasons for PHP floating-point calculation errors. In computers, floating-point numbers are represented in binary form, and binary cannot accurately represent all decimal decimals, which leads to the inaccuracy of floating-point numbers.

Convert floating point number to string using strconv.FormatFloat function Convert floating point number to string using strconv.FormatFloat function Jul 25, 2023 am 11:45 AM

Use the strconv.FormatFloat function to convert floating point numbers into strings. In the Go language, we often need to convert floating point numbers into string types for output or storage needs. The strconv package is provided in the Go language, and the FormatFloat function in it can convert floating point numbers into string types. The FormatFloat function takes three parameters: f represents the floating point number to be converted, fmt represents the format, and prec represents the number of decimal places to retain. Among them, the f parameter

An in-depth explanation of PHP BCMath: Unleashing the potential of number operations An in-depth explanation of PHP BCMath: Unleashing the potential of number operations Feb 23, 2024 am 09:10 AM

:1. Introduction to BCMath BCMath is an extension library built into PHP, which is specially used to handle large integer and floating point number operations. It provides a wealth of functions to perform various mathematical operations such as addition, subtraction, multiplication, division, square, and square root, and supports digital representation in multiple bases. 2. Advantages of BCMath Compared with the arithmetic operators and functions natively provided by PHP, BCMath mainly has the following advantages: Higher precision: BCMath’s operation results can retain more significant digits, which is useful for calculations involving large numbers. scenes are particularly important. Wider range: BCMath can handle larger numbers than PHP's native data types, thus avoiding overflow or loss of precision issues. Richer features: BCMath provides

How to convert string to float in PHP How to convert string to float in PHP Mar 27, 2024 pm 12:48 PM

Converting a string to a floating point number is a common operation in PHP and can be accomplished through built-in methods. First make sure that the string is in a legal floating point format before it can be successfully converted to a floating point number. The following will detail how to convert a string to a floating point number in PHP and provide specific code examples. 1. Use (float) cast In PHP, the simplest way to convert a string into a floating point number is to use cast. The way to force conversion is to add (float) before the string, and PHP will automatically convert it

How to round down a floating point number using the Math.Truncate function in C# How to round down a floating point number using the Math.Truncate function in C# Nov 18, 2023 pm 02:02 PM

How to use the Math.Truncate function in C# to round down floating point numbers requires specific code examples. In C# programming, we often encounter situations where floating point numbers need to be rounded down. Among them, rounding down is a common operation and can be implemented using the Math.Truncate function in C#. This article will introduce the usage of Math.Truncate function in detail and provide specific code examples. Math.Truncate function is a mathematical function in C#, used to convert a floating

See all articles