call(back)
Algorithms & Data StructuresmediumSign in to star problems

Round Numeric Strings I

You are given numeric values as strings, for example "3.45", "-2.5", or "123456789123456789123456789.5". The values may be far too large for built-in integer or float types in most languages, and converting to float would lose precision — so treat this as pure string manipulation.

Round each value to the nearest integer, rounding half away from zero, and return the result as a string with no leading zeros and never "-0".

Example:

"3.45"  -> "3"      "2.5"   -> "3"      "-2.5"  -> "-3"
"-0.4"  -> "0"      "9.99"  -> "10"     "999.5" -> "1000"
"123456789123456789123456789.5" -> "123456789123456789123456790"

Hints

Hint 1

Only the first fractional digit matters for direction: with half-away-from-zero, the magnitude rounds up exactly when that digit is 5 or more.

Hint 2

Split off the sign and round the magnitude, reattaching the sign only when the result is not 0. Rounding up is big-integer addition: walk the integer digits right to left carrying a 1, and prepend a digit if the carry survives (999 to 1000).

Asked at