Algorithm
-
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.
-
Check Validity:
- Ensure that the input is a valid number. If not, handle the error appropriately.
-
Determine Formatting Options:
- Determine the currency symbol, decimal separator, and thousands separator based on user input or use default values.
-
Split the Number:
- Split the number into integer and decimal parts.
-
Format Decimal Part:
- If there is a decimal part, format it according to the desired decimal separator.
-
Format Integer Part:
- Format the integer part by adding thousands separators.
-
Combine Integer and Decimal Parts:
- Combine the formatted integer and decimal parts with the appropriate separator.
-
Add Currency Symbol:
- Append or prepend the currency symbol to the formatted number string.
-
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
#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
#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
#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
Demonstration
JavaScript Programing to Format Numbers as Currency Strings-DevsEnv