Question

If I have the following code which grabs an array of values and adds them all together, how can I then round them down to the nearest 10000 using PHP?

Here's the code I currently have

$rows = $db->get("sales");
$sales = 0;
foreach($rows as $row) {
    $stock = $sales + $row['sales'];
}
return $sales;

An example result would be

146740

How could I then make that returned as

140000

Although if I had a number greater than 1 million, how could I have that returned as just 1 million?

Was it helpful?

Solution

Divide by 10000, use floor to round down to an integer, then multiply by 10000:

$x = 146740;
$x = 10000 * floor($x/10000);

Or subtract the remainer:

$x = 146740;
$x = $x - ($x % 10000);

To extend this to 1 million, you can do:

if ($x > 1000000) {
    $divisor = 1000000;
} elseif ($x > 10000) {
    $divisor = 10000;
} else {
    $divisor = 1;
}
$x = $x - ($x % divisor);

OTHER TIPS

you could divide the value by 1000. If it is integer 146740/1000 = 146. And after that multiply by 1000 will give 146000

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top