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.
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