Accountants, scientists and tax offices round numbers by different rules, and floats get halves
wrong (round(4.835, 2) is 4.83). Write round_decimal(text, places, mode) that rounds the
decimal number written in text to places digits after the point, exactly, and returns the
result as a string.
text is an optional sign (+ or -), digits, and optionally a point followed by digits; there
is at least one digit in total, and the whole part may start with zeros ("12.345", "-0.005",
"7", "+3.10", ".25", "-.75", "007.5").
mode is one of:
"half_up": nearest; an exact half goes away from zero"half_even": nearest; an exact half goes to the neighbour whose last digit is even"down": toward zero (drop the extra digits)"floor": toward minus infinity"ceiling": toward plus infinity
The answer has exactly places digits after the point (no point at all when places is 0), no
leading zeros before the point (a single 0 when the whole part is zero), no + sign, and a -
only when the rounded value is not zero.
Examples
Input: text = "4.835", places = 2, mode = "half_up"
Output: "4.84"
Input: text = "-0.125", places = 2, mode = "half_even"
Output: "-0.12"
Input: text = "-0.004", places = 2, mode = "floor"
Output: "-0.01"
Input: text = "-0.004", places = 2, mode = "ceiling"
Output: "0.00"
Input: text = "007.5", places = 0, mode = "half_up"
Output: "8"
Constraints
texthas at most 40 digits, plus an optional sign and point, in the format described above
Goals
- Represent a decimal string exactly as an integer and a scale
- Implement five rounding rules from their definitions
- Format a result with a fixed number of decimals and no negative zero