开发者

How to round down to nearest X number - pseudocode for VBScript

开发者 https://www.devze.com 2023-01-11 14:42 出处:网络
I\'m trying to round down a number to the nearest say 15, 20, 30. ie 726 to the nearest 30 is 700 714 to the nearest 15 is 700

I'm trying to round down a number to the nearest say 15, 20, 30. ie

726 to the nearest 30 is 700

714 to the nearest 15 is 700 etc

VBScr开发者_如何转开发ipt code would be very helpful but pseudocode would also be a huge help!

EDIT: Sorry, I forgot to say, that 726 is really a time expressed as an int, ie 07:26. So this should be 07:00, not 690

EDIT Again: I'm just extracting the minute and using the code people have answered with. Hopefully this will help someone else too. Thanks!

Thanks


Pseudo code:

diff = num mod nearest
return num - diff

So 726 mod 30 = 6

726 - 6 = 720

vbscript:

Function GetNearest(num, nearest)
    Dim diff = num mod nearest
    GetNearest = num - diff
End Function


You listed a bunch of languages in your tags. I'm going with C#, but a more generic algorithm:

int n = 726;
int q = 30;
int r = Math.Floor(n / q) * q;


another way to do it is just to use integer division: 726 / 30 * 30 = 720

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号