JavaScript: Create a specified currency formatting from a given number
JavaScript fundamental (ES6 Syntax): Exercise-126 with Solution
Write a JavaScript program to create a specified currency format from a given number.
- Use Intl.NumberFormat to enable country / currency sensitive formatting.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
// Define the 'toCurrency' function.
const toCurrency = (n, curr, languageFormat = undefined) =>
Intl.NumberFormat(languageFormat, { style: 'currency', currency: curr }).format(n);
// Test the 'toCurrency' function with sample inputs.
console.log(toCurrency(123456.789, 'EUR')); // Output: "€123,456.79"
console.log(toCurrency(123456.789, 'USD', 'en-us')); // Output: "$123,456.79"
console.log(toCurrency(123456.789, 'USD', 'fa')); // Output: "۱۲۳٬۴۵۶٫۷۹ US$"
console.log(toCurrency(322342436423.2435, 'JPY')); // Output: "¥322,342,436,423"
console.log(toCurrency(322342436423.2435, 'JPY', 'fi')); // Output: "322 342 436 423 ¥"
Output:
€123,456.79 $123,456.79 $۱۲۳٬۴۵۶٫۷۹ ¥322,342,436,423 322 342 436 423 ¥
Flowchart:
Live Demo:
See the Pen javascript-basic-exercise-126-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to convert a float-point arithmetic to the Decimal mark form and It will make a comma separated string from a number.
Next: Write a JavaScript program to iterate over a callback n times.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-126.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics