Concept

How can a generalized rounding function round values to different decimal places?

ComputerScienceOne / Generalized Rounding

"Recall that the standard math library provides a round() function that rounds a number to the nearest whole number. We’ve had need to round to cents as well. We now have the ability to write a function to do this for us. Before we do, however, let’s think more generally. What if we wanted to round to the nearest tenth? Or what if we wanted to round to the nearest 10s or 100s place? Let’s write a general purpose rounding function that allows us to specify which decimal place to round to. The most natural input values would be to specify the place using an integer exponent. That is, if we wanted to round to the nearest tenth, then we would pass it −1 as 0.1 = 10−1, −2 if we wanted to round to the nearest 100th, etc. In the other direction, passing in 0 would correspond to the usual round function, 1 to the nearest 10s spot, and so on. Moreover, we could demonstrate good code reuse (as well as procedural abstraction) by scaling the input value and reusing the functionality already provided in the math library’s round() function. We could further define a roundToCents() function that used our generalized round function.\n\nLet’s also think about organization. We could place the prototypes into a round.h header file and the corresponding definitions in a round.c source file. The contents of these two files are presented here:\n\n/**\n\n* Rounds to the nearest digit specified by the place\n\n* argument. In particular to the (10^place)-th digit\n\n*/\n\ndouble roundToPlace(double x, int place);\n\n/**\n\n* Rounds to the nearest cent\n\n*/\n\ndouble roundToCents(double x);\n\n#include <math.h>\n\n#include \"round.h\"\n\ndouble roundToPlace(double x, int place) {\n\ndouble scale = pow(10, -place);\n\ndouble rounded = round(x * scale) / scale;\n\nreturn rounded;\n\n}\n\ndouble roundToCents(double x) {\n\nreturn roundToPlace(x, -2);\n\n}\n\nObserve that neither of these files contains a main() function. By themselves they would not be able to be compiled into an executable program. We’ve essentially built a small library of rounding functions. We could compile them though into a binary object file using gcc (something like gcc -c round.c). We could then link into the object file when compiling an executable program that uses these functions."

Related Ideas

How can a generalized rounding function round values to different decimal places? | ComputerScienceOne | Bifalgorithm | Bifalgorithm