Tutorialspoint
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".
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".
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)
NumberTCS (Tata Consultancy Services)KPMG
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Extract the sign of the number and work with absolute value.
 Step 2: Convert number to fixed 2 decimal places and split into integer and decimal parts.
 Step 3: Process the integer part from right to left, adding commas every 3 digits.
 Step 4: Build the formatted integer string with proper comma placement.
 Step 5: Combine the dollar sign, formatted integer part, and decimal part.
 Step 6: Add the negative sign at the beginning if the original number was negative.
 Step 7: Return the complete formatted currency string.

Submitted Code :