Could anyone give me an explanation (and maybe an example) on how to strip the trailing zeros from a number using PHP.
For example:
"Lat":"37.422005000000000000000000000000","Lon":"-122.84095000000000000000000000000"
Would be turned in to:
"Lat":"37.422005","Lon":"-122.84095"
I am trying to strip the zeros to make it more readable. I tried using str_replace()
but this replaced the zeros inside the number too.
Given a number in string format and the task is to remove all leading zeros from the given string in PHP. Method 1: Using ltrim() function: The ltrim() function is used to remove whitespaces or other characters (if specified) from the left side of a string.
$num + 0 does the trick.
Algorithm. Step 1: Get the string Step 2: Count number of trailing zeros n Step 3: Remove n characters from the beginning Step 4: return remaining string.
Parameter Values Specifies a constant to specify the rounding mode: PHP_ROUND_HALF_UP - Default. Rounds number up to precision decimal, when it is half way there. Rounds 1.5 to 2 and -1.5 to -2.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With