Round Decimal Strings to a Power-of-Ten Step, No Floats
StringsModel answerLast updated
Round a decimal string to the nearest integer, then to a power-of-ten step such as 100 or 0.1, using only string and digit operations and a clearly stated tie-breaking rule.
You are given numbers as strings. They may be too long or too precise for a built-in float or fixed-width integer, so you must not convert the whole value to one. Do all the work on the characters.
Part 1: nearest integer
Write a function that takes a decimal string s and returns the nearest integer as a string.
smay start with+or-.smay contain a single decimal point, and either side of it may be empty. For example,"-.2"means-0.2and"2."means2.0.- The integer part can have thousands of digits.
- Exact halves (
...5exactly at the cut) need a rule. Choose a deterministic one, state it, and apply it consistently.
Part 2: nearest multiple of a step
Write a function that takes two strings:
s, a decimal number as above.p, a positive step that is always a power of ten, such as"1000","100","0.1"or"0.01".
Return s rounded to the nearest multiple of p, as a string.
s | p | result |
|---|---|---|
"12567" | "100" | "12600" |
"1234.678" | "0.1" | "1234.7" |
What to settle and show
- Which inputs are valid, and what happens for invalid ones.
- Your tie-breaking rule, and why it is convenient for negative numbers.
- Your output format: leading zeros, a
-0result, and whether trailing zeros are kept when the step is fractional. - Time and space complexity.
- Tests for carries (such as
999.9), tiny values, and steps larger than the number.
Hints
Hint 1
Part 1 is just Part 2 with a step of 1. Think of both as rounding to a multiple of 10^k, where k is the exponent of the step.
Hint 2
Remove the sign and glue the integer and fractional digits into one digit string. The decimal point is then a position (the length of the integer part), and the step decides how many leading digits you keep.
Hint 3
With round-half-away-from-zero you can round the magnitude and reattach the sign afterward. Only the first discarded digit matters: 5 or more means round up. Rounding up is a decimal increment with carry, where 999 becomes 1000 and an empty prefix becomes 1.
Hint 4
Handle the case where the step is larger than the number by treating the kept prefix as empty. Pad with zeros when the step is finer than the digits you have. Drop the sign if the result is zero.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Contract
I would agree on these points first.
- Valid input: an optional sign, then digits with at most one
., and at least one digit overall.".5"and"5."are valid."",".","1.2.3"and"1e5"raiseValueError. - Ties: round half away from zero, so
2.5 -> 3and-2.5 -> -3. The rule is symmetric under negation, so I round the absolute value and put the sign back at the end. It also means only the first dropped digit matters:>= 5rounds up, otherwise down. - Output: no leading zeros, no
+, and never-0. For a step10^kwithk >= 0the result is an integer string. Fork < 0it has exactly-kfractional digits, with trailing zeros kept ("1.5"with"0.001"gives"1.500"). Stripping zeros instead is a one-line change if the interviewer prefers.
Approach
Rounding to the nearest integer is the special case k = 0 of rounding to a multiple of 10^k, so one routine handles both parts.
- Split
sinto(negative, whole, frac)and join the digits asD = whole + frac. - Compute how many leading digits of
Dsurvive:keep = len(whole) - k.keep < 0: the step is more than ten times the magnitude, so the answer is 0.keep > len(D): right-padDwith zeros. The step is finer than the input.
kept = D[:keep]andnxt = D[keep], or'0'if there is no such digit.- If
nxt >= '5', add one tokeptusing schoolbook carry."999"becomes"1000", and an empty string becomes"1". - Strip leading zeros.
keptis now the answer counted in units of10^k. - Format it. For
k >= 0, appendkzeros. Fork < 0, left-pad with zeros to at least-k + 1digits and insert the point-kplaces from the right. - Attach
-only if the input was negative andkeptis not zero.
To read p, join its digits the same way. Exactly one digit must be nonzero and it must be 1. If it is at index i, then k = len(whole_p) - 1 - i. So "100" gives 2, "0.1" gives -1, ".01" gives -2 and "1.00" gives 0.
Why it is correct
Let kept be the leading digits before any increment. It equals floor(|x| / 10^k), and the remainder r lies in [0, 10^k). We need to know whether r >= 0.5 * 10^k. That holds exactly when the first dropped digit is at least 5, because the remaining digits add less than one unit of that digit's place and can never reach 10^k on their own. So the increment rule is exactly round-half-up on the magnitude, and restoring the sign gives half-away-from-zero. The carry loop covers cascades such as 9.5 -> 10.
Complexity
Time is O(n + m + |k|) for len(s) = n and len(p) = m. Each stage (parse, slice, one carry pass, format) is linear, and the |k| term for padding is bounded by the output size. Space is the same order. No bounded numeric type is used, so a 10,000-digit input is fine.
Code
DIGITS = set("0123456789")
def split_number(s: str):
"""Return (negative, whole, frac) for a decimal string."""
s = s.strip()
negative = False
if s[:1] in ("+", "-"):
negative = s[0] == "-"
s = s[1:]
whole, _, frac = s.partition(".")
if "." in frac:
raise ValueError("more than one decimal point")
if not (whole or frac):
raise ValueError("no digits")
if any(c not in DIGITS for c in whole + frac):
raise ValueError("invalid character")
return negative, whole, frac
def add_one(d: str) -> str:
"""Increment a digit string; the empty string counts as 0."""
chars = list(d)
i = len(chars) - 1
while i >= 0 and chars[i] == "9":
chars[i] = "0"
i -= 1
if i < 0:
return "1" + "".join(chars)
chars[i] = chr(ord(chars[i]) + 1)
return "".join(chars)
def round_at(negative, whole, frac, k):
"""Round to the nearest multiple of 10**k, ties away from zero."""
digits = whole + frac
keep = len(whole) - k
if keep < 0:
kept, nxt = "", "0"
else:
if keep > len(digits):
digits += "0" * (keep - len(digits))
kept = digits[:keep]
nxt = digits[keep] if keep < len(digits) else "0"
if nxt >= "5":
kept = add_one(kept)
kept = kept.lstrip("0") or "0"
is_zero = kept == "0"
if k >= 0:
mag = "0" if is_zero else kept + "0" * k
else:
f = -k
kept = kept.zfill(f + 1)
mag = kept[:-f] + "." + kept[-f:]
return ("-" if negative and not is_zero else "") + mag
def exponent_of_step(p: str) -> int:
negative, whole, frac = split_number(p)
digits = whole + frac
nonzero = [i for i, c in enumerate(digits) if c != "0"]
if negative or len(nonzero) != 1 or digits[nonzero[0]] != "1":
raise ValueError("step must be a positive power of ten")
return len(whole) - 1 - nonzero[0]
def round_to_integer(s: str) -> str:
neg, whole, frac = split_number(s)
return round_at(neg, whole, frac, 0)
def round_to_step(s: str, p: str) -> str:
k = exponent_of_step(p)
neg, whole, frac = split_number(s)
return round_at(neg, whole, frac, k)
Test cases
| Input | Output | Reason |
|---|---|---|
"-.2" | "0" | rounds to zero, sign dropped |
"2." | "2" | empty fraction |
"-2.5" | "-3" | tie goes away from zero |
"999.9" | "1000" | carry adds a digit |
"0.49999" | "0" | only the first dropped digit counts |
"+007.6" | "8" | sign and leading zeros stripped |
"12", step "1000" | "0" | step much larger than the value |
"567", step "1000" | "1000" | empty kept prefix, then increment |
"-0.04", step "0.1" | "0.0" | zero result, no sign |
"1.5", step "0.001" | "1.500" | right-padding |
".", "1.2.3", step "0.2" | ValueError | invalid input |
Common mistakes
- Looking at more than one dropped digit, or treating
0.4999...as a tie. - Forgetting the carry that grows the length (
999 -> 1000). - Returning
"-0". - Mishandling a step larger than the number, which leaves an empty prefix.
- Using
int()on huge strings. In Python this works but is quadratic-ish for very long inputs and defeats the point of the exercise.
Follow-up: half-to-even
Banker's rounding needs two more facts: whether the dropped tail is exactly half (first dropped digit is 5 and all later digits are 0), and the parity of the last kept digit. Round up if the tail is above half, or if it is exactly half and the last kept digit is odd. Otherwise truncate. The rest of the algorithm is unchanged.