Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip trailing zeros in PHP

Tags:

string

php

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.

like image 934
nhunston Avatar asked Mar 01 '11 00:03

nhunston


People also ask

How to remove. 0 in php?

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.

How remove extra zeros from decimal in PHP?

$num + 0 does the trick.

How do you remove trailing zeros from strings?

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.

How do I limit decimal places in PHP?

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.


1 Answers

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

like image 98
RobertPitt Avatar answered Sep 30 '22 18:09

RobertPitt