Home > Backend Development > PHP Problem > PHP floating point number float operation transfer to int problem

PHP floating point number float operation transfer to int problem

coldplay.xixi
Release: 2023-03-02 13:32:01
Original
3026 people have browsed it

php Floating point number float operation transfer to integer: Floating point numbers in PHP are weak types. For integers or floating point numbers whose results are integers after operations, PHP can treat them as integers. The code is [intval(round (floatval($value) * 100))].

PHP floating point number float operation transfer to int problem

php floating point number float operation transfer to integer type int:

Run this code:

$f = 0.58;
var_dump(intval($f * 100.0));
Copy after login

Maybe you think he will output 58, but in fact he outputs 57.
The reason is that as floating point data, part of its accuracy has been lost and it cannot be completely accurate. So never trust that a floating-point number result is accurate to the last digit, and never compare two floating-point numbers for equality.

Floating point numbers in PHP are weakly typed. For integers or floating point numbers whose result after operation is an integer, PHP can treat them as integers, but the type remains unchanged. But if it is not an integer after the operation, then PHP will treat the result as a strict floating point number

In actual development, we can use the following logic to solve this situation

intval(round(floatval($value) * 100));
Copy after login

Related learning recommendations: PHP programming from entry to proficiency

The above is the detailed content of PHP floating point number float operation transfer to int problem. 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