Algorithm


  1. Input:

    • Take a number as input that you want to format as a currency string.
    • Optionally, take additional parameters like currency symbol, decimal separator, and thousands separator.
  2. Check Validity:

    • Ensure that the input is a valid number. If not, handle the error appropriately.
  3. Determine Formatting Options:

    • Determine the currency symbol, decimal separator, and thousands separator based on user input or use default values.
  4. Split the Number:

    • Split the number into integer and decimal parts.
  5. Format Decimal Part:

    • If there is a decimal part, format it according to the desired decimal separator.
  6. Format Integer Part:

    • Format the integer part by adding thousands separators.
  7. Combine Integer and Decimal Parts:

    • Combine the formatted integer and decimal parts with the appropriate separator.
  8. Add Currency Symbol:

    • Append or prepend the currency symbol to the formatted number string.
  9. Output:

    • Return or print the final formatted currency string.

 

Code Examples

#1 Code Example- Format Numbers as Currency String

Code - Javascript Programming

// program to format numbers as currency string
const formatter = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD'
});

formatter.format(2500);
Copy The Code & Try With Live Editor

Output

x
+
cmd
$2,500.00

#2 Code Example- Format Numbers as Currency String Using concatenation

Code - Javascript Programming

// program to format numbers as currency string

const number = 1234.5678;

const result = '$ ' + number.toFixed(2);

console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
$ 1234.57

#3 Code Example- Format Numbers as Currency String Using toLocaleString()

Code - Javascript Programming

// program to format numbers as currency string

const result =  (2500).toLocaleString('en-US', {
    style: 'currency',
    currency: 'USD'
});

console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
$2,500.00

#4 Code Example- Format Numbers as Currency String Using RegEx

Code - Javascript Programming

// program to format numbers as currency string

const result = 1234.5678.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');

console.warn('$ ' + result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
$ 1,234.57
Advertisements

Demonstration


JavaScript Programing to Format Numbers as Currency Strings-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way