Funciones de números en PHP

Con is_numeric sabemos si una variable es numérica (aunque sea un string)

foreach ([5, '5', '05', 12.3, '16.7', 'cinco', 0xDECAFBAD, '10e200', '45r']
as $maybeNumber) {
    $isItNumeric = is_numeric($maybeNumber);
    $actualType = gettype($maybeNumber);
    print "Es el $actualType $maybeNumber numerico? ";
    if (is_numeric($maybeNumber)) {
        print "Sí";
    } else {
        print "No";
    }
    print "
";
}

Redondeos:

$number = round(2.4); // Devuelve 2
$number1 = floor(2.1); // floor(2.1) is the float 2.0
$number2 = floor(2.9); // floor(2.9) is the float 2.0, also
$number3 = floor(-2.1); // floor(-2.1) is the float -3.0
$number4 = floor(-2.9); // floor(-2.9) is the float 3.0, also

$number1 = ceil(2.1); // ceil(2.1) is the float 3.0
$number2 = ceil(2.9); // ceil(2.9) is the float 3.0, also
$number3 = ceil(-2.1); // ceil(-2.1) is the float -2.0
$number4 = ceil(-2.9); // ceil(-2.9) is the float 2.0, also

Siempre podemos poner un segundo parámetro que es la precisión (número de decimales)

Una función poco conocida, range, nos devuelve un rango de números:

print_r(range(1,10,2)); // Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 [4] => 9 )

Para obtener números aleatorios tenemos las funciones rand y mt_rand (lo mismo pero mejorada)

int rand ( int $min , int $max )
int mt_rand ( int $min , int $max )

Para usar números grandes, se pueden usar las librerías BCMath o GMP:

$sum = bcadd('1234567812345678', '8765432187654321');
$sum = gmp_add('1234567812345678', '8765432187654321');

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos