Concept

How can a general-purpose PHP function round values to a specified decimal place?

ComputerScienceOne / Quadratic Roots

"40.2. Examples 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 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. Consider the following.\n\n<?php\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\nfunction roundToPlace($x, $place) {\n\n$scale = pow(10, -$place);\n\n$rounded = round(x * $scale) / $scale;\n\nreturn $rounded;\n\n}\n\n/**\n\n* Rounds to the nearest cent\n\n*/\n\nfunction roundToCents($x) {\n\nreturn roundToPlace($x, -2);\n\n}\n\n?>\n\nWe could place these functions into a file named round.php and include them in another PHP source file."

Related Ideas

How can a general-purpose PHP function round values to a specified decimal place? | ComputerScienceOne | Bifalgorithm | Bifalgorithm