How to strip trailing zeros in PHP

You'll run into a lot of trouble if you try trimming or other string manipulations. Try this way.

$string = "37.422005000000000000000000000000";

echo $string + 0;

Outputs:

37.422005

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


Try with rtrim:

$number = rtrim($number, "0");

If you have a decimal number terminating in 0's (e.g. 123.000), you may also want to remove the decimal separator, which may be different depending on the used locale. To remove it reliably, you may do the following:

$number = rtrim($number, "0");
$locale_info = localeconv();
$number = rtrim($number, $locale_info['decimal_point']);

This of course is not a bullet-proof solution, and may not be the best one. If you have a number like 12300.00, it won't remove the trailing 0's from the integer part, but you can adapt it to your specific need.

Tags:

Php

String