How to get whole and decimal part of a number?

前端 未结 16 1142
名媛妹妹
名媛妹妹 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:41

    a short way (use floor and fmod)

    $var = "1.25";
    $whole = floor($var);     // 1
    $decimal = fmod($var, 1); //0.25
    

    then compare $decimal to 0, .25, .5, or .75

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

    Cast it as an int and subtract

    $integer = (int)$your_number;
    $decimal = $your_number - $integer;
    

    Or just to get the decimal for comparison

    $decimal = $your_number - (int)$your_number
    
    0 讨论(0)
  • 2020-11-27 03:47

    To prevent the extra float decimal (i.e. 50.85 - 50 give 0.850000000852), in my case I just need 2 decimals for money cents.

    $n = 50.85;
    $whole = intval($n);
    $fraction = $n * 100 % 100;
    
    0 讨论(0)
  • 2020-11-27 03:49

    Just to be different :)

    list($whole, $decimal) = sscanf(1.5, '%d.%d');
    

    CodePad.

    As an added benefit, it will only split where both sides consist of digits.

    0 讨论(0)
  • 2020-11-27 03:54
    $x = 1.24
    
    $result = $x - floor($x);
    
    echo $result; // .24
    
    0 讨论(0)
  • 2020-11-27 03:54

    If you can count on it always having 2 decimal places, you can just use a string operation:

    $decimal = 1.25;
    substr($decimal,-2);  // returns "25" as a string
    

    No idea of performance but for my simple case this was much better...

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