How to strip trailing zeros in PHP

Forget all the rtrims, and regular expressions, coordinates are floats and should be treated as floats, just prepend the variable with (float) to cast it from a string to a float:

$string = "37.422005000000000000000000000000";
echo (float)$string;

output:

37.422005

The actual result you have are floats but passed to you as strings due to the HTTP Protocol, it’s good to turn them back into thier natural form to do calculations etc on.

Test case: http://codepad.org/TVb2Xyy3

Note: Regarding the comment about floating point precision in PHP, see this: https://stackoverflow.com/a/3726761/353790

Leave a Comment