PHP round to integer

后端 未结 6 419
再見小時候
再見小時候 2021-01-07 22:54

I want to round a number and I need a proper integer because I want to use it as an array key. The first \"solution\" that comes to mind is:

$key = (int)roun         


        
相关标签:
6条回答
  • 2021-01-07 23:29

    Round to the nearest integer

    $key = round($number, 0);

    0 讨论(0)
  • For My Case, I have to make whole number by float or decimal type number. By these way i solved my problem. Hope It works For You.

    $value1 = "46.2";
    $value2 = "46.8";
    
    
    // If we print by round()
    echo round( $value1 );    //return float 46.0
    echo round( $value2 );    //return float 47.0
    
    
    // To Get the integer value
    echo intval(round( $value1 ));   // return int 46
    echo intval(round( $value2 ));   // return int 47
    
    0 讨论(0)
  • 2021-01-07 23:40

    To round floats properly, you can use:

    • ceil($number): round up
    • round($number, 0): round to the nearest integer
    • floor($number): round down

    Those functions return float, but from Niet the Dark Absol comment: "Integers stored within floats are always accurate, up to around 2^51, which is much more than can be stored in an int anyway."

    0 讨论(0)
  • 2021-01-07 23:50

    Integers stored within floats are always accurate, up to around 253, which is much more than can be stored in an int anyway. I am worrying over nothing.

    0 讨论(0)
  • 2021-01-07 23:52

    What about simply adding 1/2 before casting to an int?

    eg:

    $int = (int) ($float + 0.5);
    

    This should give a predictable result.

    0 讨论(0)
  • 2021-01-07 23:56

    round(), without a precision set always rounds to the nearest whole number. By default, round rounds to zero decimal places.

    So:

    $int = 8.998988776636;
    round($int) //Will always be 9
    
    $int = 8.344473773737377474;
    round($int) //will always be 8
    

    So, if your goal is to use this as a key for an array, this should be fine.

    You can, of course, use modes and precision to specify exactly how you want round() to behave. See this.

    UPDATE

    You might actually be more interested in intval:

    echo intval(round(4.7)); //returns int 5
    echo intval(round(4.3)); // returns int 4
    
    0 讨论(0)
提交回复
热议问题