Rounding a floating point number to a near-fractionThis tip submitted by Steven on 2006-04-21 19:49:32. It has been viewed 7626 times.
Rating of 6.7 with 20 votes
Say you have a float number like 3.42
You can round to a fraction decimal like this. Say you want the nearest 1/8
increment. First add 1/2 of 1/8 decimal, the value of which is .125/2 =.0625, so the math is 3.42 + .0625 = 3.4825
Now multiply by the fraction you want 3.4825 * 8 = 27.86
Then take the integer and devide by the fraction: 27 * 8 = 3.375
That's 3/8's. I've used this a lot so I know it works.
Because floating point numbers cannot be arbitrarily precise, you should not rely on this method if you need 100% precision!
Help your fellow programmers! Add a tip!