Concept

How can a generalized rounding method round numbers to any decimal place?

ComputerScienceOne / Generalized Rounding

"Recall that the math library provides a Math.round() method 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 method 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 method that allows us to specify which decimal place to round to. The most natural input 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. We could demonstrate good code reuse (as well as good procedural abstraction) by scaling the input value and reusing the functionality already provided in the math library’s Math.round() method. We could further define a roundToCents() method that used our generalized round method. Finally, we could place all of these methods into RoundUtils Java class for good organization.\n\npublic class RoundUtils {\n\npublic static double roundToPlace(double x, int place) {\n\ndouble scale = Math.pow(10, -place);\n\ndouble rounded = Math.round(x * scale) / scale;\n\nreturn rounded;\n\n}\n\npublic static double roundToCents(double x) {\n\nreturn RoundUtils.roundToPlace(x, -2);\n\n}\n\n}\n\nObserve that this class does not contain a main() method. That means that this class is not executable itself. It only provides functionality to other classes in the code base."

Related Ideas

How can a generalized rounding method round numbers to any decimal place? | ComputerScienceOne | Bifalgorithm | Bifalgorithm