开发者

Is casting to float destructive?

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 开发者_JAVA技巧(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.


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜