Skip to content
Advertisement

Is it possible to use *= operator together with round() function

I often need to use fractional modificators for my variables. Like this:

$var *= 1.5;

Yet I need the oputput to be rounded, so I need to use:

$var = round($var * 1.5);

Is is no big deal, but every single time I can not use the *= operator, and I need to write round(). Is there a shrotcut for this?

Advertisement

Answer

As $var *= 1.5; is a shortcut for $var = $var * 1.5; this means that you can’t inject any function call here. So, $var = round($var * 1.5); cannot be changed using *= notation.

As a solution you can use a user-defined function:

$var = multiplyAndRound($var, 1.5);
function multiplyAndRound($var, $multiplier) {
    return round($var * $multiplier);
}
// or with passing by refrence
$var = 1.3;
multiplyAndRound($var, 1.5);
function multiplyAndRound(&$var, $multiplier) {
    $var = round($var * $multiplier);
}

But I don’t think that this can be called “shortcut”.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement