Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,635 questions

55,370 answers

573 users

How to round an integer up to the nearest multiple of 'multiple' in PHP

1 Answer

0 votes
/*
    roundUp(n, multiple)
    --------------------
    Rounds the integer n *up* to the nearest multiple of `multiple`.

    Mathematically:
        result = ceil(n / multiple) * multiple

    We use integer arithmetic for efficiency:
        (n + multiple - 1) / multiple  → smallest integer ≥ n/m
*/

function roundUp(int $n, int $multiple): int {
    if ($multiple <= 0) {
        // Defensive programming: avoid undefined behavior.
        // In real-world code, you'd throw or handle this differently.
        return $n;
    }

    // Efficient integer rounding up:
    return intdiv($n + $multiple - 1, $multiple) * $multiple;
}

// main()
echo "roundUp(53, 20)  = " . roundUp(53, 20) . "\n";
echo "roundUp(68, 30)  = " . roundUp(68, 30) . "\n";
echo "roundUp(7, 100)  = " . roundUp(7, 100) . "\n";
echo "roundUp(119, 100) = " . roundUp(119, 100) . "\n";
echo "roundUp(781, 100) = " . roundUp(781, 100) . "\n";
echo "roundUp(1026, 100) = " . roundUp(1026, 100) . "\n";
echo "roundUp(11689, 1000) = " . roundUp(11689, 1000) . "\n";



/*
run:

roundUp(53, 20)  = 60
roundUp(68, 30)  = 90
roundUp(7, 100)  = 100
roundUp(119, 100) = 200
roundUp(781, 100) = 800
roundUp(1026, 100) = 1100
roundUp(11689, 1000) = 12000

*/

 



answered Jul 22 by avibootz

Related questions

...