Floating Point Rounding

January 8, 2013

Write a function that takes a floating point number f and an integer n and rounds the floating point number to n places after the decimal point. For instance, given the floating point number 1000/7, rounding to 3 places would produce 142.857, rounding to 2 places would produce 142.86, rounding to 1 place would produce 142.9, and rounding to 0 places would produce 143. For extra credit, allow n to be negative, indicating rounding before the decimal point; for instance, rounding 1000/7 to -1 places would produce 140.

It’s not fair to use a built-in round function if your language provides one.

Your task is to write the function described above. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.