PHP: get number of decimal digits

前端 未结 18 2222
忘了有多久
忘了有多久 2020-11-28 09:25

Is there a straightforward way of determining the number of decimal places in a(n) integer/double value in PHP? (that is, without using explode)

相关标签:
18条回答
  • 2020-11-28 10:06

    You should always be careful about different locales. European locales use a comma for the thousands separator, so the accepted answer would not work. See below for a revised solution:

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

    see localeconv

    0 讨论(0)
  • 2020-11-28 10:09

    If you want readability for the benefit of other devs, locale safe, use:

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

    see localeconv

    0 讨论(0)
  • 2020-11-28 10:09

    Less code:

    $str = "1.1234567";
    echo strpos(strrev($str), ".");
    
    0 讨论(0)
  • 2020-11-28 10:10
    $value = 182.949;
    
    $count = strlen(abs($value - floor($value))) -2; //0.949 minus 2 places (0.)
    
    0 讨论(0)
  • 2020-11-28 10:11

    First I have found the location of the decimal using strpos function and increment the strpos postion value by 1 to skip the decimal place.

    Second I have subtracted the whole string length from the value I have got from the point1.

    Third I have used substr function to get all digits after the decimal.

    Fourth I have used the strlen function to get length of the string after the decimal place.

    This is the code that performs the steps described above:

         <?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))) );
        ?>
    
    0 讨论(0)
  • 2020-11-28 10:11

    This will work for any numbers, even in scientific notation, with precision up to 100 decimal places.

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

    Result:

    7
    

    Lengthy but works without complex conditionals.

    0 讨论(0)
提交回复
热议问题