Jump to content

[SOLVED] Round up by 25


jaymc

Recommended Posts

This is not the most efficient method because you're recalculating the nearest 25 every time. Optimizing this depends on how often you're running it, and the range of numbers you're working with.

 

<pre>
<?php
	$numbers = range(0,100);
	foreach ($numbers as $number) {
		printf('%2d = ', $number);
		if ($number % 25 <= 12) {
			while ($number % 25) {
				--$number;
			}
		}
		else {
			while ($number % 25) {
				++$number;
			}
		}
		echo $number, '<br>';
	}
?>
</pre>

Link to comment
https://forums.phpfreaks.com/topic/37395-solved-round-up-by-25/#findComment-178754
Share on other sites

<?php
function roundByFactor($input, $factor)
{
$input = round($input);

$modulus = $input % $factor;

if($modulus >= ($factor / 2))
{
	$input = roundByFactor($input + $modulus, $factor);
}
else {
	$input = $input - $modulus;
}

return $input;
}

echo roundByFactor(32, 25); // outputs 25
?>

 

unfortunately it doesn't work right for negative numbers.

 

edit: sorry, fixed it, should work for decimals now.

Link to comment
https://forums.phpfreaks.com/topic/37395-solved-round-up-by-25/#findComment-178781
Share on other sites

I wrote this function before the post above was made. But I thought I would still post it.

<?php
function roundbase25($number) {
$number = round($number / 25) * 25;
return $number;
}

 

It seems to work with everything I've thrown at it.

 

This...

print "3 " . roundbase25(3) . "\n";
print "20 " . roundbase25(20) . "\n";
print "226 " . roundbase25(226) . "\n";

 

will output this...

3 0

20 25

226 225

Link to comment
https://forums.phpfreaks.com/topic/37395-solved-round-up-by-25/#findComment-178788
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.