Is casting to float destructive?

孤者浪人 提交于 2019-12-24 09:29:25

问题


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.


回答1:


NO, Casting to a float is almost always destructive.

In your example, 5.111 represented in binary is:

101.00011100011010100111111011111001110110110010001011010000111001...

A float would store 23 digits:

101.0001110001101010011 
(5.1109981536865234375)

A double would store 52 digits:

101.0001110001101010011111101111100111011011001000101
(5.1109999999999988773424774990417063236236572265625)

In this case, there wouldn't be a difference. However, in larger numbers, it can affect what you display.

For example:

1025.4995

double:

10000000001.011111111101111100111011011001000101101
(1025.499499999999898136593401432037353515625)

float:

10000000001.011111111101
(1025.499267578125)

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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/4649315/is-casting-to-float-destructive

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