Reputation: 19582
I want to find (given a number that could be a float) how to find the next multiple of 60.
I am doing the following which works:
my $nextMultiple = int($input/$constant);
$nextMultiple = ((int($nextMultiple/60)) * 60);
$nextMultiple += 60;
I actually add 60 in the last line on purpose. Is there a better way for this?
Upvotes: 1
Views: 810
Reputation: 386461
Next highest:
# 121 => 180 -119 => -60
# 120 => 180 -120 => -60
# 119 => 120 -121 => -120
$n - ($n % 60) + 60
Next largest:
# 121 => 180 -119 => -120
# 120 => 180 -120 => -180
# 119 => 120 -121 => -180
$n + ( $n >= 0 ? +1 : -1 ) * ( 60 - (abs($n) % 60) )
$n % 60 == 0
will tell you if $n is a multiple of 60.
Upvotes: 2
Reputation: 62109
If you want multiples of 60 to be unchanged:
use POSIX 'ceil';
my $next_multiple = ceil(($input/$constant)/60) * 60;
If you want multiples of 60 to be bumped up to the next multiple (as your existing code does):
use POSIX 'floor';
my $next_multiple = (1 + floor(($input/$constant)/60)) * 60;
Upvotes: 1