John Davidson

decimal - PHP wrong round precision

0 comments
Message:


Hi !


I've been trying to round a number with PHP but I got a precision error.


$test = 53.974999994;
echo round($test, 2);

The result I want is 53.98.


But this code gives me 53.97.


Can somebody tell me why ?


Thanks !



My Answer:
The issue you are facing is due to the way floating point numbers are represented in computers. When you have a number like 53.974999994, it may not be represented exactly as that in memory due to the limitations of floating point precision.

In this case, the number 53.974999994 is actually being stored as something like 53.974999993999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999

Rate this post

5 of 5 based on 6795 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us