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 generalized rounding function round values to different decimal places?ComputerScienceOne · Generalized Rounding
- How is generalized rounding introduced in PHP?ComputerScienceOne · Generalized Rounding
- How can a PHP program calculate and round a monthly loan payment?ComputerScienceOne · Paying the Piper
- How can a generalized rounding method round numbers to any decimal place?ComputerScienceOne · Generalized Rounding
- How can a loan amortization schedule handle rounded payments in C?ComputerScienceOne · Paying the Piper
- Why might a program need generalized rounding beyond whole numbers?ComputerScienceOne · Function Pointers
- How can PHP libraries and math functions be used?ComputerScienceOne · Comments
- How do you declare functions and specify their return values in PHP?ComputerScienceOne · Declaring Functions