简体   繁体   English

pdo_sqlsrv驱动程序如何将浮点类型转换为字符串?

[英]how pdo_sqlsrv driver convert float type to string?

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. 我将某些表的列类型设置为float并将长度设置为53,将其值设置为38.8,当我使用sqlsrv驱动程序进行查询时,就可以了,它的显示值为38.8。 But,when i use pdo_sqlsrv driver for a query ,it's show value is 38.799999999999997, it's why? 但是,当我使用pdo_sqlsrv驱动程序进行查询时,它的显示值为38.799999999999997,这是为什么?

Decimal number 38.8 is periodic when converted to binary: 转换为二进制时,十进制数38.8是周期性的

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: 其实并不重要:由于您已经建立了只需要8位小数的功能,因此在丢弃其余部分时应该获得正确的值:

ini_set('precision', 30);
var_dump( 38.8, number_format(38.8, 8) );
float(38.7999999999999971578290569596)
string(11) "38.80000000"

However, if 8 th 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. 但是,如果实际上小数点后8 对您来说很重要,则应将列类型切换为DECIMAL ,它在内部将数字存储为字符串,从而保留了精确的十进制表示形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM