Get number of digits before decimal point

前端 未结 25 1958
独厮守ぢ
独厮守ぢ 2020-12-28 11:53

I have a variable of decimal type and I want to check the number of digits before decimal point in it. What should I do? For example, 467.45 should

25条回答
  •  Happy的楠姐
    2020-12-28 11:53

    TLDR all the other answers. I wrote this in PHP, and the math would be the same. (If I knew C# I'd have written in that language.)

    $input=21689584.999;
    
        $input=abs($input);
    $exp=0;
    do{
      $test=pow(10,$exp);
    
      if($test > $input){
        $digits=$exp;
      }
      if($test == $input){
        $digits=$exp+1;
      }
      $exp++;
    }while(!$digits);
    if($input < 1){$digits=0;}
    echo $digits;
    

    I don't doubt there's a better way, but I wanted to throw in my $.02

    EDIT:

    I php-ized the code I mentioned in my comments, but did away with the int conversion.

    function digitCount($input){
      $digits=0;
      $input=abs($input);
        while ($input >= 1) {
          $digits++;
          $input=$input/10;
          //echo $input."
    "; } return $digits; } $big=(float)(PHP_INT_MAX * 1.1); echo digitCount($big);

提交回复
热议问题