Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out the nearest bigger multiple of (n) PHP

Tags:

php

logic

I have a requirement where users are forced to choose the multiple of (n) quantity of a product.

The (n) value is set with each product that can be any number.

customer can only purchase the quantity of product in the multiple of (n) quantity set with product.

Suppose if (n) is 5 and user entered quantity as 4 and says Add to Cart. I have to add quantity of that product as 5 automatically.

and if user entered 6 as quantity then I have to add the 10 quantity of that product.

How I go about that?

I am not getting what logic should be applied here.

like image 354
Daric Avatar asked Jun 23 '11 09:06

Daric


People also ask

How do you find the closest multiple of a number?

Given two numbers n and x, we need to calculate the smallest value of x that is closest to given number n. We need to find a k such that x*k is closest to n. If we do k = n/x, we get a value of k that may not lead to maximum. We can get closest by comparing the values floor(n/x) * x and ceil(n/x) * x.

How do you find the nearest multiple of 5?

If you need to round a number to the nearest multiple of 5, you can use the MROUND function and supply 5 for number of digits. The value in B6 is 17 and the result is 15 since 15 is the nearest multiple of 5 to 17.

How do you find the next multiple of 10?

The first 10 multiples of 10 are 10, 20, 30, 40, 50, 60, 70, 80, 90 and 100.


2 Answers

$entered_quantity = 6;
$suppose_n = 5;

$quantity = ceil($entered_quantity / $suppose_n) * $suppose_n;

echo $quantity;

prints 10

like image 91
jous Avatar answered Sep 20 '22 18:09

jous


that's not php specific; what you wonna do is to compute.

ceiling(q / n) * n

where q is the user's quantity, n is the multiplicity

like image 31
blabla999 Avatar answered Sep 20 '22 18:09

blabla999