problem with floating values

主宰稳场 提交于 2019-12-29 09:52:23

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/6503994/problem-with-floating-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!