Skip to main content
Participating Frequently
May 25, 2007
Answered

rounding number to nearest 500

  • May 25, 2007
  • 5 replies
  • 1491 views
also trying to round a number to the nearest 500

this number range is from 1 to 1 million.

i have looked into ceiling but i don't think it can do what i need.
I tried using len() and cfset to break apart the number and dynamically increasing/decreasing it to suit my needs but thats not doing it reliably enough.

Finally i tried a straight up cfif statement woriing on the number ranges but i am overloading the if statement.

Any ideas on a simple coding solution for this? just wanna look at a number thats between 1 and 1 million and round it to the hearest 500 or 100.
    This topic has been closed for replies.
    Correct answer tclaremont
    Try this code, where NearestNo should be set to whatever "closest value" you want.

    <CFSET NearestNo = 500>

    <cfloop index="foobar" from="745" to="755">
    <CFSET TheAnswer = #Round(foobar/nearestno)# * #nearestno#>
    #Foobar# = #TheAnswer#<br>
    </CFLOOP>

    5 replies

    Inspiring
    May 25, 2007
    Yes I think you need to clearly define what you want.

    Do you want the nearest 500 (ROUND). 749 rounds to 500 and 750 rounds
    to 1000.

    Do want the nearest 500 under the number (FLOOR). 501 floors to 500 and
    999 floors to 500.

    Do want the nearest 500 over the number (CEILING). 501 ceilings to 1000
    and 999 ceilings to 1000.

    tclaremont
    Inspiring
    May 25, 2007
    Great!

    tclaremont
    Inspiring
    May 25, 2007
    Ian, I modified my post while you were responding. I think I have the code above correct now.
    GaneshaAuthor
    Participating Frequently
    May 25, 2007
    actually this worked great thanks
    Inspiring
    May 25, 2007
    tclaremont wrote:
    > This will need some more developing, but here is the gist of it...
    >
    > Divide the number by 500, take the integer of the result, and then multiply by
    > 500.
    >
    > 5223 / 500 = 10.446
    >
    > Int(10.446) = 10
    >
    > 10 * 500 = 5000
    >

    Yes, this is close. It will give you the highest 500 (floor) under a
    given number. To get to the nearest 500 you will need to round the
    decimal before you drop the fraction. Just adding .5 is an easy way to
    do this.

    5423 / 500 = 10.846
    10.846 + .5 = 11.346
    int(11.346) = 11
    11 * 500 = 5500

    tclaremont
    tclaremontCorrect answer
    Inspiring
    May 25, 2007
    Try this code, where NearestNo should be set to whatever "closest value" you want.

    <CFSET NearestNo = 500>

    <cfloop index="foobar" from="745" to="755">
    <CFSET TheAnswer = #Round(foobar/nearestno)# * #nearestno#>
    #Foobar# = #TheAnswer#<br>
    </CFLOOP>