Round a Decimal String Without Using Floats
StringsModel answerLast updated
Round a decimal number given as a string to the nearest integer, then to its last significant digit, using digit-level arithmetic and carry handling instead of floating-point types.
Decimal string rounding
You receive a decimal number as a string. Write functions that round it without converting it to a floating-point value. The input can be longer than a double can represent exactly.
Part 1: nearest integer
Return the integer closest to the number, as a string. Exact halves round away from zero.
"3.5"gives"4""100.01"gives"100""-2.5"gives"-3"
Part 2 (follow-up): round at the last significant digit
Find the last nonzero digit of the number and remove it by rounding at the position just before it. The value's magnitude must be preserved.
"124900"gives"125000""12.49"gives"12.5"
A number with zero or one significant digit has nothing to round to. Return it in normalized form (for example "0.03" stays "0.03", and "0" stays "0").
Input and output conventions
- The input may have an optional leading
+or-, leading or trailing zeros, and a missing integer part or missing fractional part (".5","5."). Reject anything else, such as an empty string, a lone".", or letters. - Never output negative zero:
"-0.4"rounds to"0". - Do not round more than once.
12.49becomes12.5, not13. - In Part 2 the output keeps fractional digits up to the rounding position, so
"9.95"gives"10.0". - The input can have thousands of digits, so a carry such as
"999.9"becoming"1000"must be handled.
Explain your approach, state the time and space complexity, and give working code.
Hints
Hint 1
Split the number into a sign, one combined digit string (integer digits followed by fractional digits), and the count of integer digits. Both parts then become 'keep the first k digits and look at digit k'.
Hint 2
Whether to round up depends only on the first discarded digit (5 or more means up). Rounding up is a grade-school increment: trailing 9s become 0 and the carry moves left. If every kept digit was 9, prepend a 1, which shifts the decimal point one place right.
Hint 3
For Part 2, set k to the index of the last nonzero digit. If the rounding position lies inside the integer part, pad zeros back on. Round only once, and do not emit a negative sign if the result is all zeros.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Floats are the wrong tool here. 0.1 and 100.01 have no exact binary representation, many languages use banker's rounding by default (Python's round(2.5) is 2), and a string with 30 digits loses precision as a double. The reliable approach is to do the arithmetic on the digits themselves.
Conventions to settle first
- Tie rule: half away from zero (
2.5to3,-2.5to-3). Round the magnitude and reattach the sign afterwards, since the rule is symmetric. - Valid input: optional sign, digits, at most one dot, and at least one digit overall. Anything else raises an error.
- Negative zero: drop the sign if every digit of the result is zero.
- Part 2 meaning: "last significant digit" is the last nonzero digit, so trailing zeros are ignored (
12.4900behaves like12.49). Numbers with fewer than two significant digits are returned normalized.
Representation
Parse into (neg, D, p):
negis the sign.Dis the integer digits followed by the fractional digits, with no dot.pis the number of integer digits (a missing integer part counts as"0").
For "12.49", D = "1249" and p = 2.
One primitive: round at a position
round_at(D, k) keeps the first k digits of D and inspects D[k]:
- If
D[k]is missing or below 5, return the kept prefix unchanged. - Otherwise add 1 to the prefix. Scan from the right, turning each
9into0. The first non-9 digit is incremented and the scan stops. - If every digit was
9, prepend1and report that the number grew by one digit, so the integer length becomesp + 1.
This is correct because the first discarded digit alone decides which side of the halfway point the tail is on. Later digits cannot change the decision.
Using the primitive
- Part 1:
k = p. Output the kept digits as an integer, with leading zeros stripped and the sign applied only if the result is nonzero. - Part 2:
k = j, wherejis the index of the last nonzero digit inD. Rounding there removes that digit.- If a carry grew the number, add 1 to both
pandk. - If
k < p, the rounding happened inside the integer part, so appendp - kzeros (125becomes125000). - Otherwise, the digits after position
pform the fractional part (125withp = 2becomes12.5). - If there are fewer than two nonzero digits, skip rounding and return the number with leading zeros removed from the integer part and trailing zeros removed from the fraction.
- If a carry grew the number, add 1 to both
Complexity
- Time: O(n) for one parse, one carry scan, and one formatting pass.
- Space: O(n) for the output, which can be one character longer than the input. This is optimal.
Code
DIGITS = set("0123456789")
def _parse(s):
s = s.strip()
neg = False
if s[:1] in ("+", "-"):
neg = s[0] == "-"
s = s[1:]
int_part, _, frac_part = s.partition(".")
body = int_part + frac_part
if not body or any(c not in DIGITS for c in body) or s.count(".") > 1:
raise ValueError("invalid numeric string")
int_part = int_part or "0"
return neg, int_part + frac_part, len(int_part)
def _round_at(d, k):
"""Keep first k digits of d, rounding half up on the magnitude.
Returns (digits, grew)."""
head = list(d[:k])
if k >= len(d) or d[k] < "5":
return "".join(head), False
i = k - 1
while i >= 0 and head[i] == "9":
head[i] = "0"
i -= 1
if i >= 0:
head[i] = chr(ord(head[i]) + 1)
return "".join(head), False
return "1" + "".join(head), True
def _format(neg, d, p):
int_s = d[:p].lstrip("0") or "0"
frac = d[p:]
out = int_s + ("." + frac if frac else "")
if neg and any(c != "0" for c in d):
out = "-" + out
return out
def round_to_integer(s):
neg, d, p = _parse(s)
head, grew = _round_at(d, p)
return _format(neg, head, len(head))
def round_last_significant(s):
neg, d, p = _parse(s)
nz = [i for i, c in enumerate(d) if c != "0"]
if len(nz) <= 1:
return _format(neg, d[:p] + d[p:].rstrip("0"), p)
k = nz[-1]
head, grew = _round_at(d, k)
if grew:
p += 1
k += 1
if k < p:
head += "0" * (p - k)
return _format(neg, head, p)
Worked checks
| Input | Part 1 | Part 2 |
|---|---|---|
3.5 | 4 | 4 |
100.01 | 100 | 100.0 |
-2.5 | -3 | -3 |
-0.4 | 0 | -0.4 |
9.95 | 10 | 10.0 |
999.9 | 1000 | 1000.0 |
124900 | 124900 | 125000 |
12.4900 | 12 | 12.5 |
0.0049 | 0 | 0.005 |
.5 | 1 | 0.5 |
Common mistakes
- Using floats or built-in
round. This causes representation error, banker's rounding, and precision loss on long inputs. - Rounding twice. Turning
12.49into12.5and then rounding again gives13. Always decide from the original digits. - Dropping the carry.
"999"must become"1000", and the decimal point position must shift with it. - Producing
-0. Check the final digits before attaching a minus sign. - Treating trailing zeros as significant in Part 2.
- Skipping input validation for forms like
".5","5.","+3",".", and"".
Trade-offs and extensions
If the interviewer prefers 100 over 100.0 in Part 2, strip trailing fractional zeros in the formatter. This is a one-line change. If other tie rules (half-even, half-up toward positive infinity) are needed, only the "should we round up" test changes, since it would also inspect the last kept digit or the sign. In production, Python's decimal module or Java's BigDecimal with an explicit rounding mode does the same job, but writing it by hand shows that you understand what those libraries do.