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

10,601

Solution 1

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

Solution 2

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;

Solution 3

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

Share:
10,601
Igor K
Author by

Igor K

Updated on September 03, 2022

Comments

  • Igor K
    Igor K over 1 year

    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

    VBScript 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

    • Daniel Renshaw
      Daniel Renshaw over 13 years
      I think you mean 726 (rounded down) to the nearest 30 is 720 and 714 (rounded down) to the nearest 15 is 705.
    • Igor K
      Igor K over 13 years
      Yes I forgot to mention that its really times, please see the question. Really sorry, my mistake
    • Oded
      Oded over 13 years
      can you please further clarify how time like 5:45pm would appear in your int representation and if the last 2 digits are ever over 59...
    • Igor K
      Igor K over 13 years
      Thanks Oded, all sorted with your original code
  • akonsu
    akonsu over 13 years
    i thought that modulo is a remainder, that is 726 mod 30 = 6 :)
  • Igor K
    Igor K over 13 years
    Thanks Oded, your answer was perfect, just my question wasnt.
  • akonsu
    akonsu over 13 years
    i think there was a typo in your original answer that is why i put my comment.
  • Igor K
    Igor K over 13 years
    Actually, in VBScript, I've just got the minute out and used this function, works perfectly, thanks so much
  • akonsu
    akonsu over 13 years
    Math.Floor(n / q) is the same as n / q if all the variables are integers.
  • Toby
    Toby over 13 years
    @akonsu: True, but not necessarily in all languages. I thought I'd make the flooring more explicit for use with scripting languages where the types can get muddled.
  • Igor K
    Igor K over 13 years
    Thanks, appreciate this is just the same as using MOD