How to strip trailing zeros in PHP

Solution 1:

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

Solution 2:

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.

Solution 3:

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

Solution 4:

In my case, I did the following, extending other answers here:

rtrim((strpos($number,".") !== false ? rtrim($number, "0") : $number),".");

Because I also had to remove the decimal if a whole number was being shown

As an example, this will show the following numbers

2.00, 1.00, 28.50, 16.25 

As

2, 1, 28.5, 16.25

Rather than

2., 1., 28.5, 16.25

Which, to me, is not showing them correctly.

Latest edit also stops numbers such as "100" from being rtrim'ed to 1, by only trimming the rightmost 0's if a decimal is encountered.

Solution 5:

You can also use floatval(val);.

 <?php
 echo floatval( "37.422005000000000000000000000000" );
 ?>

results in

37.422005