Round a Decimal String to Significant Digits
Updated
Problem statement
Given a non-negative decimal number as a string number and a positive integer digits, round the number to that many significant decimal digits using round-half-up: round up when the first discarded digit is 5 or greater, and round down otherwise.
The input contains only digits and at most one decimal point. It has at least one digit and no sign or exponent. Leading and trailing zeroes may appear.
Return ordinary decimal notation with no decimal point when the rounded result is an integer. Otherwise remove trailing fractional zeroes. Return 0 when the value is zero.
Function
roundSignificant(number: String, digits: int) → StringExamples
Example 1
number = "124.23"digits = 2return = "120"The first two significant digits are 1 and 2; the next digit is 4, so the result is 120.
Example 2
number = "0.009876"digits = 3return = "0.00988"Leading zeroes are not significant, and the next digit rounds 987 upward.
Example 3
number = "999.5"digits = 3return = "1000"Rounding propagates a carry into a new digit.
Constraints
1 <= number.length <= 200000.1 <= digits <= 200000.- The input is a valid non-negative decimal string with at most one decimal point.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Iterate Canonical IPv6 AddressesOpenAI · ONSITE INTERVIEW
- Add Decimal Strings ExactlyMeta · PHONE SCREEN · ONSITE INTERVIEW
- Add Two Numeric Strings with CarryZipRecruiter · ONSITE INTERVIEW
- Add Two Numbers Given as Digit ArraysCapital One · ONSITE INTERVIEW
- Add Signed Character ArraysByteDance · PHONE SCREEN
- Per-Segment SpeedingOnePay · PHONE SCREEN
- Flip Rows and Columns, Count ZerosNutanix · OA
- Format a Centered Pagination BarMixpanel · PHONE SCREEN
- Multiply StringsZillow · PHONE SCREEN
- Subtract Two Large Number StringsStackAdapt · PHONE SCREEN