
Problem
Solution
Submissions
Format Number as Currency
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a JavaScript program to format a given number as currency with proper thousand separators and decimal places. The function should handle both positive and negative numbers and format them according to standard currency display rules.
Example 1
- Input: num = 1234567.89
- Output: "$1,234,567.89"
- Explanation:
- The input number is 1234567.89.
- Add dollar sign at the beginning.
- Insert commas every three digits from right to left in the integer part.
- Ensure two decimal places are displayed.
- Result is "$1,234,567.89".
- The input number is 1234567.89.
Example 2
- Input: num = -5000
- Output: "-$5,000.00"
- Explanation:
- The input number is -5000 (negative).
- Keep the negative sign at the beginning.
- Add dollar sign after the negative sign.
- Add comma separator for thousands.
- Add two decimal places (.00). Result is "-$5,000.00".
- The input number is -5000 (negative).
Constraints
- -999,999,999.99 ≤ num ≤ 999,999,999.99
- Always display exactly 2 decimal places
- Use comma as thousand separator
- Handle negative numbers with proper sign placement
- Time Complexity: O(n), where n is the number of digits
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Convert the number to string and handle the sign separately
- Split the number into integer and decimal parts
- Add commas to the integer part by iterating from right to left
- Ensure exactly 2 decimal places are displayed
- Combine sign, dollar symbol, formatted integer, and decimal parts