Rounding to the nearest fraction (i.e. specific decimal place)

Posted by Dan on Sep 25, 2009 @ 8:55 AM

I'm working on some "star rating" code and I really wanted to round numbers of to the nearest fraction. While the math is really basic, my math skills are rusty and this took me longer to solve than I care to admit. So I thought I'd just blog the solution for anyone else that might find it useful:

round( value/fraction ) * fraction

Like I said, it's very basic math but is very handy when you want to round to something other than to the closest integer.

Categories: JavaScript, SQL, HTML/ColdFusion, Flex/Flash, Java

2 Comments

  • Barbara McLennan's Gravatar
    Barbara McLennan
    I am using some code to convert decimals to fractions, which works well, but I get crazy fractions like 4 273/500. At the moment I have heaps of lines of code to manually replace the ridiculous fractions.

    I'm looking for a better way, that's how I found your blog, but I'm not sure how to use

    round( value/fraction ) * fraction

    can you give me an example maybe using my example fraction?
  • @Barbara:

    The "value" variable is the original value you want to round to a fractional value.

    The "fraction" variable would be the fraction you want to round to. For example, if you wanted to round the number to the nearest quarter, you'd use 0.25 for the value of fraction.

    So if you take 1 1/6 and want to round to quarters, you would have:

    (1.166667/0.25) * 0.25 = 1.25

    So if you take 1 1/10 and want to round to quarters, you would have:

    (1.1/0.25) * 0.25 = 1.0

    You can change the "fraction" value to whatever level of precision you want.

Comments for this entry have been disabled.