programing

PHP: 소수 자릿수를 가져옵니다.

goodcopy 2022. 11. 6. 13:23
반응형

PHP: 소수 자릿수를 가져옵니다.

PHP에서 정수/이중값의 소수 자릿수를 결정하는 간단한 방법이 있습니까? (즉, 사용하지 않고)explode)

$str = "1.23444";
print strlen(substr(strrchr($str, "."), 1));

코드 감소:

$str = "1.1234567";
echo (int) strpos(strrev($str), ".");

int에 던져보고 숫자에서 그걸 뺀 다음 남은 걸 세어보는 것도 좋을 거야.

function numberOfDecimals($value)
{
    if ((int)$value == $value)
    {
        return 0;
    }
    else if (! is_numeric($value))
    {
        // throw new Exception('numberOfDecimals: ' . $value . ' is not a number!');
        return false;
    }

    return strlen($value) - strrpos($value, '.') - 1;
}


/* test and proof */

function test($value)
{
    printf("Testing [%s] : %d decimals\n", $value, numberOfDecimals($value));
}

foreach(array(1, 1.1, 1.22, 123.456, 0, 1.0, '1.0', 'not a number') as $value)
{
    test($value);
}

출력:

Testing [1] : 0 decimals
Testing [1.1] : 1 decimals
Testing [1.22] : 2 decimals
Testing [123.456] : 3 decimals
Testing [0] : 0 decimals
Testing [1] : 0 decimals
Testing [1.0] : 0 decimals
Testing [not a number] : 0 decimals

다양한 숫자 형식으로 작동하는 솔루션이 필요했고 다음과 같은 알고리즘을 생각해냈습니다.

// Count the number of decimal places
$current = $value - floor($value);
for ($decimals = 0; ceil($current); $decimals++) {
    $current = ($value * pow(10, $decimals + 1)) - floor($value * pow(10, $decimals + 1));
}

// Count the total number of digits (includes decimal places)
$current = floor($value);
for ($digits = $decimals; $current; $digits++) {
    $current = floor($current / 10);
}

결과:

input:    1
decimals: 0
digits:   1

input:    100
decimals: 0
digits:   3

input:    0.04
decimals: 2
digits:   2

input:    10.004
decimals: 3
digits:   5

input:    10.0000001
decimals: 7
digits:   9

input:    1.2000000992884E-10
decimals: 24
digits:   24

input:    1.2000000992884e6
decimals: 7
digits:   14

다음 항목을 사용하여 반환된 값에 소수점(실제 10진수 값, 100.00과 같은 소수점을 표시하도록 포맷된 값)이 있는지 여부를 확인했습니다.

if($mynum - floor($mynum)>0) {has decimals;} else {no decimals;} 

예를 들어 다음과 같습니다.

<?php

$floatNum = "120.340304";
$length = strlen($floatNum);

$pos = strpos($floatNum, "."); // zero-based counting.

$num_of_dec_places = ($length - $pos) - 1; // -1 to compensate for the zero-based count in strpos()

?>

이건 절차상 엉터리이며, 생산 코드에 사용하는 것은 권장하지 않습니다.하지만 그게 널 시작할 수 있을 거야.

<?php

test(0);
test(1);
test(1.234567890);
test(-123.14);
test(1234567890);
test(12345.67890);

function test($f) {
    echo "f = $f\n";
    echo "i = ".getIntCount($f)."\n";
    echo "d = ".getDecCount($f)."\n";
    echo "\n";
}

function getIntCount($f) {
    if ($f === 0) {
        return 1;
    } elseif ($f < 0) {
        return getIntCount(-$f);
    } else {
        return floor(log10(floor($f))) + 1;
    }
}

function getDecCount($f) {
    $num = 0;
    while (true) {
        if ((string)$f === (string)round($f)) {
            break;
        }
        if (is_infinite($f)) {
            break;
        }

        $f *= 10;
        $num++;
    }
    return $num;
}

출력:

f = 0
i = 1
d = 0

f = 1
i = 1
d = 0

f = 1.23456789
i = 1
d = 8

f = -123.14
i = 3
d = 2

f = 1234567890
i = 10
d = 0

f = 12345.6789
i = 5
d = 4

후행 0을 고려하는 함수는 다음과 같습니다.

function get_precision($value) {
    if (!is_numeric($value)) { return false; }
    $decimal = $value - floor($value); //get the decimal portion of the number
    if ($decimal == 0) { return 0; } //if it's a whole number
    $precision = strlen($decimal) - 2; //-2 to account for "0."
    return $precision; 
}

다른 개발, 로케일 세이프를 위해 읽기 쉽게 하려면 다음 명령을 사용합니다.

function countDecimalPlacesUsingStrrpos($stringValue){
    $locale_info = localeconv();
    $pos = strrpos($stringValue, $locale_info['decimal_point']);
    if ($pos !== false) {
        return strlen($stringValue) - ($pos + 1);
    }
    return 0;
}

localconv 참조

솔루션

$num = "12.1234555";
print strlen(preg_replace("/.*\./", "", $num)); // 7

설명.

양식.*\.소수점 앞의 모든 문자를 의미합니다.

이 경우 문자열은 다음 세 글자로 구성됩니다.12.

preg_replace함수는 이러한 캐시된 문자를 빈 문자열로 변환합니다.""(두 번째 파라미터).

이 경우, 다음의 문자열이 표시됩니다.1234555

strlenfunction은 보유 문자열의 문자 수를 카운트합니다.

$decnumber = strlen(strstr($yourstr,'.'))-1

이건 어때?

$iDecimals = strlen($sFull%1);

내부

정수는 십진수가 없기 때문에 답은 항상 0입니다.

더블/플로트

이중 또는 부동 숫자는 근사치입니다.따라서 정의된 소수 자릿수는 없습니다.

예를 들어 다음과 같습니다.

$number = 12.00000000012;
$frac = $number - (int)$number;

var_dump($number);
var_dump($frac);

출력:

float(12.00000000012)
float(1.2000000992884E-10)

여기서 두 가지 문제를 볼 수 있습니다.두 번째 숫자는 과학적 표현을 사용하고 있으며 1.2E-10은 아닙니다.

스트링

정수/플로트가 포함된 문자열의 경우 소수점을 검색할 수 있습니다.

$string = '12.00000000012';
$delimiterPosition = strrpos($string, '.');
var_dump(
  $delimiterPosition === FALSE ? 0 : strlen($string) - 1 - $delimiterPosition
);

출력:

int(11)

먼저 다음을 사용하여 소수점 위치를 찾았습니다.strpos기능하고 증가하다strpos소수 자릿수를 건너뛰려면 포션 값을 1로 지정합니다.

둘째, point1에서 얻은 값에서 전체 문자열 길이를 뺍니다.

세 번째로 사용한 것은substr소수점 뒤의 모든 숫자를 가져오는 함수입니다.

넷째, 저는strlen소수점 뒤의 문자열 길이를 가져오는 함수입니다.

위의 순서를 실행하는 코드는 다음과 같습니다.

     <?php
        $str="98.6754332";
        echo $str;
        echo "<br/>";
        echo substr( $str, -(strlen($str)-(strpos($str, '.')+1)) );
        echo "<br/>";
        echo strlen( substr( $str, -(strlen($str)-(strpos($str, '.')+1))) );
    ?>

항상 다른 장소에 주의해야 합니다.유럽의 로케일에서는, 수천 개의 구분자로 쉼표를 사용하고 있기 때문에, 받아들여진 회답은 기능하지 않습니다.수정된 솔루션에 대해서는 아래를 참조하십시오.

 function countDecimalsUsingStrchr($stringValue){
        $locale_info = localeconv();
        return strlen(substr(strrchr($stringValue, $locale_info['decimal_point']), 1));
    }

localconv 참조

이 방법은 소수점 이하 100자리까지 정확하게 과학적 표기법으로도 사용할 수 있습니다.

$float = 0.0000005;

$working = number_format($float,100);
$working = rtrim($working,"0");
$working = explode(".",$working);
$working = $working[1];

$decmial_places = strlen($working);

결과:

7

장황하지만 복잡한 조건 없이 작동합니다.

$value = 182.949;

$count = strlen(abs($value - floor($value))) -2; //0.949 minus 2 places (0.)

언급URL : https://stackoverflow.com/questions/2430084/php-get-number-of-decimal-digits

반응형