Problem with floating values

I have weird php floating point behavior

$array_test["test"]= round($value,2); //first I round up a value echo $array_test["test"]; //0,66 $s_array_test= serialize($array_test); //serializing the array var_dump($s_array_test) // (...)s:4:"test";d:0.66000000000000003108624468950438313186168670654296875;}(...) 

This is a pretty nasty reason why a serialized array is stored in db to use more space ...

How to fix it?

THX

0
source share
2 answers

First of all, read the section on floats in the manual http://php.net/manual/en/language.types.float.php

Floating point numbers have limited precision. Although it depends on the system, PHP usually uses the IEEE 754 double-precision format, which will give the maximum relative error due to rounding of the order of 1.11e-16. Non-elementary arithmetic operations can lead to large errors, and, of course, it is necessary to correct the error when several operations are exacerbated.

In addition, rational numbers that are accurately represented as floating point numbers in base 10, such as 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which are used internally, regardless of the size of the mantissa Therefore, they cannot be converted to their internal binary copies without a slight loss of accuracy. This can lead to confusing results: for example, gender ((0,1 + 0,7) * 10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118 ....

Therefore, never trust the action of floating-point numbers to the last digit and never compare floating-point numbers for equality. If higher accuracy is required, arbitrary mathematical precision functions and gmp functions are available.

You can use sprintf() (instead of round() ) to convert a float to a fixed-size string

 sprintf('%.2f', $float); 

But I suggest you create and use a real database schema. You don't need a database at all if you just put unstructured rows in it. Instead, you can use simple flatfiles.

+3
source

it can behave this way because the data type in the table is varchar or any non-generic data type. I am not saying that this is the only reason, but it may be one of them.

+1
source

Source: https://habr.com/ru/post/919880/


All Articles