How to get whole and decimal part of a number?

前端 未结 16 1149
名媛妹妹
名媛妹妹 2020-11-27 03:10

Given, say, 1.25 - how do I get \"1\" and .\"25\" parts of this number?

I need to check if the decimal part is .0, .25, .5, or .75.

相关标签:
16条回答
  • 2020-11-27 03:57

    This code will split it up for you:

    list($whole, $decimal) = explode('.', $your_number);
    

    where $whole is the whole number and $decimal will have the digits after the decimal point.

    0 讨论(0)
  • 2020-11-27 03:57

    This is the way which I use:

    $float = 4.3;    
    
    $dec = ltrim(($float - floor($float)),"0."); // result .3
    
    0 讨论(0)
  • 2020-11-27 03:59
    $n = 1.25;
    $whole = floor($n);      // 1
    $fraction = $n - $whole; // .25
    

    Then compare against 1/4, 1/2, 3/4, etc.


    In cases of negative numbers, use this:

    function NumberBreakdown($number, $returnUnsigned = false)
    {
      $negative = 1;
      if ($number < 0)
      {
        $negative = -1;
        $number *= -1;
      }
    
      if ($returnUnsigned){
        return array(
          floor($number),
          ($number - floor($number))
        );
      }
    
      return array(
        floor($number) * $negative,
        ($number - floor($number)) * $negative
      );
    }
    

    The $returnUnsigned stops it from making -1.25 in to -1 & -0.25

    0 讨论(0)
  • 2020-11-27 03:59
    val = -3.1234
    
    fraction = abs(val - as.integer(val) ) 
    
    0 讨论(0)
  • 2020-11-27 04:00

    PHP 5.4+

    $n = 12.343;
    intval($n); // 12
    explode('.', number_format($n, 1))[1]; // 3
    explode('.', number_format($n, 2))[1]; // 34
    explode('.', number_format($n, 3))[1]; // 343
    explode('.', number_format($n, 4))[1]; // 3430
    
    0 讨论(0)
  • 2020-11-27 04:01

    Brad Christie's method is essentially correct but it can be written more concisely.

    function extractFraction ($value) 
    {
        $fraction   = $value - floor ($value);
        if ($value < 0)
        {
            $fraction *= -1;
        }
    
        return $fraction;
    }
    

    This is equivalent to his method but shorter and hopefully easier to understand as a result.

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