Problem 131631 · hard · Phase 01 Prerequisites & Setup

The Rounding Desk

strings · functions · integer division · modulo · rounding · conditionals

Accountants, scientists and tax offices round numbers by different rules, and floats get halves wrong (round(2.675, 2) is 2.67). 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 ("12.345", "-0.005", "7", "+3.10", ".25", "-.75").

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), a single 0 before the point when the whole part is zero, no + sign, and a - only when the rounded value is not zero.

Examples

Input:  text = "2.675", places = 2, mode = "half_up"
Output: "2.68"

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"

Constraints

  • text has at most 40 digits; 0 <= places <= 12

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
Starting Python…