开发者

problem with floating values

开发者 https://www.devze.com 2023-03-15 17:08 出处:网络
I ve got a strange php behaviour with floating value $array_test[\"test\"]= round($value,2); //first I round up a value

I ve got a strange php behaviour with floating value

$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 pretty annoying cause the serialized array is stored into a db a use more space...

开发者_运维知识库How to fix this ?

thx


First of all read the section about 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 typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error progragation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

So never trust floating number results to the last digit, and never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

You may use sprintf() (instead of round()) to convert the float into a fixed-sized string

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

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


it may behave like this because data type in table is varchar or any non -numeric datatype. i don't say this is the only reason but it can be one of them ..

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号