PHP round to integer

后端 未结 6 420
再見小時候
再見小時候 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: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
    

提交回复
热议问题