How to strip trailing zeros in PHP

PhpString

Php Problem Overview


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.

Php Solutions


Solution 1 - 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

Solution 2 - Php

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 - 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

Solution 4 - Php

You can also use floatval(val);.

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

results in

> 37.422005

Solution 5 - Php

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 6 - Php

Most of these solutions will trim significant digits in numbers such as "100" (no trailing decimal). Here's a simple solution that doesn't have this problem:

function TrimTrailingZeroes($nbr) {
    if(strpos($nbr,'.')!==false) $nbr = rtrim($nbr,'0');
    return rtrim($nbr,'.') ?: '0';
}

I think that covers all the different scenarios.

>>> TrimTrailingZeroes('0')
=> "0"
>>> TrimTrailingZeroes('01')
=> "01"
>>> TrimTrailingZeroes('01.0')
=> "01"
>>> TrimTrailingZeroes('01.01')
=> "01.01"
>>> TrimTrailingZeroes('01.010')
=> "01.01"
>>> TrimTrailingZeroes('.0')
=> "0"
>>> TrimTrailingZeroes('.1')
=> ".1"
>>> TrimTrailingZeroes('.10')
=> ".1"
>>> TrimTrailingZeroes('3141592653589793.238462643383279502880000000000000000000000000000')
=> "3141592653589793.23846264338327950288"

Solution 7 - Php

If you want to strip the excess zeros away from the end but only to a certain decimal place, this is a useful expression to do just that (for example 0.30000 will show 0.30 and 0.0003000 will show 0.0003).

preg_replace("/(?<=\\.[0-9]{2})[0]+\$/","",$number);

Of course the {2} controls the decimal place limit.

Solution 8 - Php

You should use the round function which is more able to manipulate numbers than a replace.

round('37.422005000000000000000000000000', 32); 
//float(37.422005)

round('-122.84095000000000000000000000000', 32); 
//float(-122.84095)

The resulting rounded number will be based upon your precision (default 14) setting.

Solution 9 - Php

Trims trailing zeroes, but only after the decimal place -- we wouldn't want to convert 100 -> 1, for example. It will also strip the period if only zeros follow it.

function trim_zeros($str) {
    if(!is_string($str)) return $str;
    return preg_replace(array('`\.0+$`','`(\.\d+?)0+$`'),array('','$1'),$str);
}

Solution 10 - Php

If you want a solution that accepts a minimum and maximum amount of decimal places, this should work:

/**
 * Displays up to 4 decimal places, with a minimum of 2 decimal places, trimming unnecessary zeroes
 *
 * @param mixed $number
 * @param int $minimumDecimals
 * @param int $maximumDecimals
 * @return string
 */
function rate_format($number, int $minimumDecimals = 2, int $maximumDecimals = 4): string
{
    $formatted = number_format($number, $maximumDecimals, '.', ',');
    $minimumLength = strpos($formatted, '.') + $minimumDecimals + 1;
    $extra = rtrim(substr($formatted, $minimumLength), "0");
    return substr($formatted, 0, $minimumLength) . $extra;
}


// rate_format("1.2500") returns "1.25"
// rate_format("1.2525") returns "1.2525"
// rate_format("1.25256") returns "1.2526"
// rate_format("1") returns "1.00"

This is hard coded to use the US locale, but should be easily adjusted for other locales.

Solution 11 - Php

Remove Trailing zeros + Thousand Separator

function specialFormat($number,  $decimals = 8)
{
    return rtrim(rtrim(number_format($number, $decimals), '0'), '.');
}

input: 0.00000008 => output: 0.00000008
input: 1560.1854500 => output: 1,560.18545
input: 1560.00 => output: 1,560

Solution 12 - Php

For me, I need a further solution to convert exponential values and simple numbers like 10000 to the last non-zero significant digit

/* Convert any value to the least significant value */
function toDecimal($val) {
 
  // Convert any exponential sign to proper decimals
  $val = sprintf("%lf", $val);

  if (strpos($val, '.') !== false) {
      $val = rtrim(rtrim($val, '0'), '.');
  }

  return $val;
}

// Test cases
echo toDecimal(1000.000) . "\n";
echo toDecimal(1E-5) . "\n";
echo toDecimal(1E+5) . "\n";
echo toDecimal(1234.56) . "\n";
echo toDecimal(1234.5700) . "\n";
echo toDecimal(1234000) . "\n";
echo toDecimal(-1e10) . "\n";

// Results
1000
0.00001
100000
1234.56
1234.57
1234000
-10000000000

Solution 13 - Php

You can use rtrim() ( http://www.php.net/manual/en/function.rtrim.php ):

rtrim( "37.422005000000000000000000000000" , "0" )

Just make sure that there will be a decimal point.

Solution 14 - Php

hmm, interesting. I have used this:

// remove leading zeros
$output = ltrim ($output, "0");
	
// remove trailing 0s.
$temp=explode(".",$output);
$temp[1]=rtrim($temp[1],"0");
$output = $temp[0];
if (!empty($temp[1])) $output.='.'.$temp[1];
	
return $output;

This removes trailing 0s from the number AFTER the first decimal point. Otherwise a number like 100 becomes 1.

Since I was doing a comparison, using the float technique caused problems. Hope this helps?

Solution 15 - Php

preg_replace will do the trick:

$lat=preg_replace('/0+$/','',$lat);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnhunstonView Question on Stackoverflow
Solution 1 - PhpRobertPittView Answer on Stackoverflow
Solution 2 - PhpjweyrichView Answer on Stackoverflow
Solution 3 - PhpOkonomiyaki3000View Answer on Stackoverflow
Solution 4 - PhpFarrayView Answer on Stackoverflow
Solution 5 - PhpWarren SergentView Answer on Stackoverflow
Solution 6 - PhpmpenView Answer on Stackoverflow
Solution 7 - Phpscott klarrView Answer on Stackoverflow
Solution 8 - PhpWilliam DurandView Answer on Stackoverflow
Solution 9 - PhpmpenView Answer on Stackoverflow
Solution 10 - PhpDevonView Answer on Stackoverflow
Solution 11 - PhpArash YounesiView Answer on Stackoverflow
Solution 12 - PhpJoe KuanView Answer on Stackoverflow
Solution 13 - PhplinepoglView Answer on Stackoverflow
Solution 14 - PhpDanView Answer on Stackoverflow
Solution 15 - PhpShadView Answer on Stackoverflow