Problem · String
Format a Signed Integer with Commas
Learn this problemProblem statement
Given a signed integer value, return its base-10 representation with a comma between every group of three digits, counting from the right.
Keep a leading minus sign before all digits. Do not add leading zeros or a plus sign.
Function
formatWithCommas(value: int) → StringExamples
Example 1
value = 1234return = "1,234"Reading from the right, the final three digits form one group, so one comma precedes 234.
Example 2
value = -9876543return = "-9,876,543"The magnitude is split into 9, 876, and 543; the minus sign remains at the front.
Example 3
value = 0return = "0"A one-digit value needs no separator.
Constraints
-2^31 <= value <= 2^31 - 1.- The result contains only decimal digits, comma separators, and an optional leading minus sign.