开发者

How to strip trailing zeros in 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 re开发者_如何学编程placed the zeros inside the number too.


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.


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


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.


You can also use floatval(val);.

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

results in

37.422005


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.


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"


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);
}


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.


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.


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


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


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.


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?


preg_replace will do the trick:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜