i have been looking around for a function in php or a solution that will simply allow me to count to number of decimal places in a number.

example

0.477 > 3 decimal places

18.09090 > 5 decimal places

can anyone help in suggesting a way i can simply count the decimal places in a number like this
, eqvalent to this type of javascript code

$p_file = "0.477";
$v_fileLength = $p_file.length; // --> 3

thanks in advance

    you could explode() on the . and then use strlen() but i suspect there is a better way.

      yeah thats what i have done

      $v_fileFloat = "0.87687";
      $v_fileFloatb = explode(".", $v_fileFloat);

      echo $v_fileFloatb[0]."<br>".$v_fileFloatb[1];

      $v_fileLength = strlen($v_fileFloatb[0]);
      $v_fileLength2 = strlen($v_fileFloatb[1]);

      this is probably the easist way to go

      thanks for the help

        there should be a math way of doing it, but my math skills suck, hopeful some one will enlighten us.

          They are strings? Not doubles?
          strlen($string) - strcspn($string, '.') - 1;

          If they're doubles you'd probably just get the display precision because floating-point arithmetic doesn't really do "decimal places".

            Alternatively, perhaps:

            $p_file = "0.477";
            echo strlen(strrchr($p_file, '.')) -1; // 3
            

            ?

              2 years later

              Old topic, I know, but for the Google'rs:

              function countDecimals($fNumber)
              {
              	$fNumber = floatval($fNumber);
              
              for ( $iDecimals = 0; $fNumber != round($fNumber, $iDecimals); $iDecimals++ );
              
              return $iDecimals;
              }
                Write a Reply...