How to get whole and decimal part of a number?

前端 未结 16 1231
名媛妹妹
名媛妹妹 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 04:01

    Not seen a simple modulus here...

    $number         = 1.25;
    $wholeAsFloat   = floor($number);   // 1.00
    $wholeAsInt     = intval($number);  // 1
    $decimal        = $number % 1;      // 0.25
    

    In this case getting both $wholeAs? and $decimal don't depend on the other. (You can just take 1 of the 3 outputs independently.) I've shown $wholeAsFloat and $wholeAsInt because floor() returns a float type number even though the number it returns will always be whole. (This is important if you're passing the result into a type-hinted function parameter.)

    I wanted this to split a floating point number of hours/minutes, e.g. 96.25, into hours and minutes separately for a DateInterval instance as 96 hours 15 minutes. I did this as follows:

    $interval = new \DateInterval(sprintf("PT%dH%dM", intval($hours), (($hours % 1) * 60)));
    

    I didn't care about seconds in my case.

提交回复
热议问题