Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...