铸造浮动是否具有破坏性?
在 PHP 中,我知道我们不应该在没有 bcmath 之类的东西的情况下对浮点数进行数学运算,但是仅仅将字符串转换为浮点数的行为是否具有破坏性?
像 (float)'5.111' == '5.111'
这样的表达式总是为真吗?或者当数字转换时,转换本身会将其更改为类似 5.1110000000000199837
的内容?
主要原因是,就像我使用 (int)
转义进入数据库的整数值一样,我想以同样的方式使用 (float)
,而无需依靠引号和我的转义函数。
In PHP, I know we shouldn't do math on floats without things like bcmath, but is the mere act of casting a string to float destructive?
Will expressions like (float)'5.111' == '5.111'
, always be true? Or will the cast itself change that to something like 5.1110000000000199837
as the number is converted?
The main reason is, just as I use (int)
to escape integer values going into a database, I would like to use (float)
in the same way, without having to rely on quotes and my escape function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,转换为浮动几乎总是具有破坏性。
在您的示例中,以二进制表示的 5.111 为:
浮点型可存储 23 位数字:
双精度型可存储 52 位数字:
在这种情况下,不会有任何差异。但是,如果数量较多,它可能会影响您显示的内容。
例如:
1025.4995
double:
float:
您可以看到精度在大约 8 位数字后开始急剧下降。
双精度数将舍入为 1025.4995,而浮点数将为 1025.4993
NO, Casting to a float is almost always destructive.
In your example, 5.111 represented in binary is:
A float would store 23 digits:
A double would store 52 digits:
In this case, there wouldn't be a difference. However, in larger numbers, it can affect what you display.
For example:
1025.4995
double:
float:
You can see the precision starts to drop off dramatically after around 8 digits.
The double would round to 1025.4995 whereas the float would be 1025.4993
您不应该使用 (int) 来转义整数值。使用参数化查询并将输入类型设置为“int”。一个更好的方法!
有关 mysql/php 中的示例,请参阅:
http://us.php.net/manual/en/mysqli.prepare.php
You shouldn't use (int) to escape integer values. Use a parametrized query and set the type of your input to 'int'. A much better way!
for an example in mysql/php see:
http://us.php.net/manual/en/mysqli.prepare.php
这取决于小数部分是否可以精确地用二进制表示(请参阅二进制中的分数)。例如,0.5 有精确的二进制表示,但 0.1 没有。如果该数字没有精确的表示形式,则再次打印时您可能会看到不同的结果。
It depends on whether or not the fractional part can be represented exactly in binary (see Fractions in binary). For example, 0.5 has an exact binary representation but 0.1 does not. If the number does not have an exact representation, you are likely to see a different result when printing it again.