Analysis of troublesome floating point operations in php

高洛峰
Release: 2023-03-03 17:40:02
Original
843 people have browsed it

This article mainly introduces the troublesome floating-point number operations in PHP. It analyzes the use of PHP's round function for floating-point number operations in the form of examples. Friends in need can refer to it

This article analyzes the troublesome floating-point number operations in PHP with examples. floating point arithmetic. Share it with everyone for your reference, the details are as follows:

When doing e-commerce, it is inevitable to calculate the price, and then I discovered a pitfall in php. The correct value should be calculated by mouth, but the calculated value in php will be different from yours

Please Look at the code below:

$price=69.1; $count=100; $total=$price*$count-6910; echo $total;
Copy after login

Guess the value of the variable $total. Run this code and the output will be: -9.09494701773E-13
How to solve this problem?

Use the round function

The code is modified to:

$price=69.1; $count=100; $total=round($price*$count)-6910; echo $total;
Copy after login

The problem is solved, the output result is 0, correct

I hope this article will be helpful to everyone in PHP programming.

For more articles related to the analysis of troublesome floating-point operations in PHP, please pay attention to 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!