KatInterview

Round a Decimal String Without Using Floats

StringsModel answer
MediumModel answerStringsstringscarry-propagationrounding

Last 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.49 becomes 12.5, not 13.
  • 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.