Asked  7 Months ago    Answers:  5   Viewed   32 times

I want a php function which returns 55 when calling it with 52.

I've tried the round() function:

echo round(94, -1); // 90

It returns 90 but I want 95.

Thanks.

 Answers

64

This can be accomplished in a number of ways, depending on your preferred rounding convention:

1. Round to the next multiple of 5, exclude the current number

Behaviour: 50 outputs 55, 52 outputs 55

function roundUpToAny($n,$x=5) {
    return round(($n+$x/2)/$x)*$x;
}

2. Round to the nearest multiple of 5, include the current number

Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 50

function roundUpToAny($n,$x=5) {
    return (round($n)%$x === 0) ? round($n) : round(($n+$x/2)/$x)*$x;
}

3. Round up to an integer, then to the nearest multiple of 5

Behaviour: 50 outputs 50, 52 outputs 55, 50.25 outputs 55

function roundUpToAny($n,$x=5) {
    return (ceil($n)%$x === 0) ? ceil($n) : round(($n+$x/2)/$x)*$x;
}
Wednesday, March 31, 2021
 
redrom
answered 7 Months ago
87

Check out http://www.php.net/manual/en/function.round.php

<?php

echo round(3.6451895227869, 2);

?>

EDIT Try using this custom function http://www.php.net/manual/en/function.round.php#102641

<?php 
function round_up ( $value, $precision ) { 
    $pow = pow ( 10, $precision ); 
    return ( ceil ( $pow * $value ) + ceil ( $pow * $value - ceil ( $pow * $value ) ) ) / $pow; 
} 

echo round_up(3.63333333333, 2);  // 3.64

?>
Wednesday, July 28, 2021
 
eliotlencelot
answered 3 Months ago
22

add these code into the top of your script

@set_magic_quotes_runtime(false);
ini_set('magic_quotes_runtime', 0);
Wednesday, August 18, 2021
 
Warrior
answered 2 Months ago
43
/**
 * Round a number up to the nearest multiple of $n.
 *
 * @param int $int  Number to round.
 * @param int $n    Round to the nearest $n.
 *
 * @return int
 */
function round_up_to_nearest_n($int, $n) {
    return ceil($int / $n) * $n;
}
echo round_up_to_nearest_n(74268, 50000); //Outputs 100000

Divide by the number you want to round against, do the rounding, then multiply by it again.

Saturday, August 21, 2021
 
Teno
answered 2 Months ago
29

Use round() instead of ceil().

5 * round($n / 5);

ceil() rounds a floating point number up to its next integer in sequence. round() will round to the nearest integer using standard rounding rules.

Monday, August 23, 2021
 
Dev
answered 2 Months ago
Dev
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :