Nice programing

PHP에서 후행 0을 제거하는 방법

nicepro 2020. 11. 22. 20:31
반응형

PHP에서 후행 0을 제거하는 방법


안녕하세요 누구든지 PHP를 사용하여 숫자에서 후행 0을 제거하는 방법에 대한 설명 (그리고 아마도 예)을 줄 수 있습니다.

예를 들면 :

"Lat":"37.422005000000000000000000000000","Lon":"-122.84095000000000000000000000000"

다음으로 제출됩니다.

"Lat":"37.422005","Lon":"-122.84095"

더 읽기 쉽게 0을 제거하려고합니다. 나는 사용을 시도 str_replace()했지만 이것은 숫자 안의 0도 대체했습니다 (doh).

감사합니다 = D


모든 rtrim과 정규 표현식을 잊어 버리십시오. 좌표는 부동 소수점으로 취급되어야합니다. 변수를 앞에 추가하여 (float)문자열에서 부동 소수점으로 캐스트하십시오.

$string = "37.422005000000000000000000000000";
echo (float)$string;

산출:

37.422005

실제 결과는 수레이지만 HTTP 프로토콜로 인해 문자열로 전달되므로 계산 등을 수행하기 위해 원래 형식으로 되 돌리는 것이 좋습니다.

테스트 케이스 : http://codepad.org/TVb2Xyy3

참고 : PHP의 부동 소수점 정밀도에 대한 주석은 https://stackoverflow.com/a/3726761/353790을 참조하십시오.


rtrim으로 시도하십시오 .

$number = rtrim($number, "0");

당신이 공의 (예 : 123.000)의 10 진수 종료가있는 경우, 당신은 할 수 있습니다 또한 제거 할 소수 구분 될 수있다, 사용 된 지역에 따라 다르지 . 안정적으로 제거하려면 다음을 수행하십시오.

$number = rtrim($number, "0");
$locale_info = localeconv();
$number = rtrim($number, $locale_info['decimal_point']);

물론 이것은 방탄 솔루션이 아니며 최상의 솔루션이 아닐 수도 있습니다. 12300.00과 같은 숫자가있는 경우 정수 부분에서 후행 0을 제거하지는 않지만 특정 요구에 맞게 조정할 수 있습니다.


트리밍이나 기타 문자열 조작을 시도하면 많은 문제가 발생합니다. 이 방법을 시도하십시오.

$string = "37.422005000000000000000000000000";

echo $string + 0;

출력 :

37.422005

당신은 또한 사용할 수 있습니다 floatval(val);.

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

결과

37.422005


이러한 솔루션의 대부분은 "100"(후행 소수점 없음)과 같은 숫자의 유효 숫자를 자릅니다. 이 문제가없는 간단한 해결책은 다음과 같습니다.

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

나는 그것이 모든 다른 시나리오를 포함한다고 생각합니다.

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

초과 0을 끝에서 제거하고 특정 소수 자릿수까지만 제거하려는 경우이 작업을 수행하는 데 유용한 식입니다 (예 : 0.30000은 0.30을 표시하고 0.0003000은 0.0003을 표시 함).

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

물론 {2}은 소수점 이하 자릿수를 제어합니다.


제 경우에는 다음을 수행하여 여기에 다른 답변을 확장했습니다.

rtrim((strpos($number,".") !== false ? rtrim($number, "0") : $number),".");

정수가 표시되면 소수점도 제거해야했기 때문에

예를 들어 다음과 같은 숫자가 표시됩니다.

2.00, 1.00, 28.50, 16.25 

같이

2, 1, 28.5, 16.25

보다는

2., 1., 28.5, 16.25

나에게는 올바르게 표시되지 않습니다.

또한 최근 편집은 소수점이있는 경우 맨 오른쪽 0 만 잘라내어 "100"과 같은 숫자가 1로 rtrim '되지 않도록합니다.


예를 들어 100-> 1로 변환하고 싶지는 않습니다. 또한 뒤에 0 만 있으면 마침표를 제거합니다.

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

.a보다 숫자를 조작 할 수 있는 round 함수사용해야합니다 replace.


나를 위해 지수 값과 10000과 같은 간단한 숫자를 0이 아닌 마지막 유효 숫자로 변환하는 추가 솔루션이 필요합니다.

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

rtrim () ( http://www.php.net/manual/en/function.rtrim.php )을 사용할 수 있습니다 .

rtrim( "37.422005000000000000000000000000" , "0" )

소수점이 있는지 확인하십시오.


흠, 흥미 롭군요. 나는 이것을 사용했다 :

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


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.


preg_replace will do the trick:

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

참고URL : https://stackoverflow.com/questions/5149129/how-to-strip-trailing-zeros-in-php

반응형