I set some table's column type to float and length to 53, set it's value is 38.8, when i use sqlsrv driver for a query, it's ok , it's show value is 38.8. But,when i use pdo_sqlsrv driver for a query ,it's show value is 38.799999999999997, it's why?
Asked
Active
Viewed 220 times
0
-
2All Floats (in a database or in code) don't store exact decimal values. See this answer I wrote before - same thing applies. http://stackoverflow.com/a/12291065/1450077 – Fluffeh Oct 09 '14 at 08:14
1 Answers
0
Decimal number 38.8 is periodic when converted to binary:
100110.1100110011001100110011001100110011001100110011001100110011001100110
^^^^
Repeats forever
Thus it cannot be stored exactly in a computer if you chose a regular numeric format (which always have fixed storage sizes).
It doesn't really matter: since you've established you only want 8 decimals, you should get the correct value when discarding the rest:
ini_set('precision', 30);
var_dump( 38.8, number_format(38.8, 8) );
float(38.7999999999999971578290569596)
string(11) "38.80000000"
However, if 8th decimal is actually important for you, you should switch the column type to DECIMAL
, which stores numbers internally as strings, thus keeps the exact decimal representation.

Álvaro González
- 142,137
- 41
- 261
- 360