nhunston
nhunston

Reputation: 1367

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 replaced the zeros inside the number too.

Upvotes: 87

Views: 85186

Answers (16)

Softumba
Softumba

Reputation: 1

function trimTrailingZeros($number, $decimal_separator){
    //Split the number by the decimal separator
    $array = explode($decimal_separator, $number);
    //the first item in the array is the whole number
    $whole_number = $array[0];
    //the second item in the array are the decimal values
    $decimal_values= $array[1];
    //remove trailing zeros from the decimal values using rtrim()
    $decimal_values = rtrim($decimal_values,'0');
    //if decimal values is not empty string, add the decimal separator;
    $point=$decimal_values?$decimal_separator:'';
    //return the adjusted number;
    return $whole_number.$point.$decimal_values;
}

Upvotes: -1

Arash Younesi
Arash Younesi

Reputation: 1760

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

Upvotes: 4

William Durand
William Durand

Reputation: 5519

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.

Upvotes: 3

Devon Bessemer
Devon Bessemer

Reputation: 35337

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.

Upvotes: 3

mpen
mpen

Reputation: 282885

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"

Upvotes: 8

jweyrich
jweyrich

Reputation: 32240

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.

Upvotes: 55

Warren Sergent
Warren Sergent

Reputation: 2597

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.

Upvotes: 10

RobertPitt
RobertPitt

Reputation: 57268

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

Upvotes: 156

Joe Kuan
Joe Kuan

Reputation: 119

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

Upvotes: 1

Dan
Dan

Reputation: 9

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?

Upvotes: 0

mpen
mpen

Reputation: 282885

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

Upvotes: 3

scott klarr
scott klarr

Reputation: 69

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.

Upvotes: 6

Okonomiyaki3000
Okonomiyaki3000

Reputation: 3696

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

Upvotes: 42

Farray
Farray

Reputation: 8528

You can also use floatval(val);.

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

results in

37.422005

Upvotes: 9

linepogl
linepogl

Reputation: 9335

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.

Upvotes: 0

Shad
Shad

Reputation: 15451

preg_replace will do the trick:

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

Upvotes: -3

Related Questions