JavaScript: Convert Number to Currency Format #codingtips

Posted by

Format number as currency in JavaScript

Format number as currency in JavaScript

When working with financial data in JavaScript, it’s important to be able to format numbers as currency. This can be achieved using the `toLocaleString` method in JavaScript.

Example:

Let’s say we have a number representing a dollar amount:

let amount = 1000;
let formattedAmount = amount.toLocaleString('en-US', {style: 'currency', currency: 'USD'});
console.log(formattedAmount); // output: $1,000.00
    

Explanation:

In the above example, we use the `toLocaleString` method with the following parameters:

  • 'en-US' – the locale parameter to specify the format based on US standards.
  • {style: 'currency', currency: 'USD'} – an options object specifying the style as currency and the currency type as USD.

Conclusion:

Formatting numbers as currency in JavaScript is essential for displaying financial data in a user-friendly and professional manner. The `toLocaleString` method provides a simple and effective way to achieve this formatting.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@ModernJavaScript
6 months ago

Want more?? Subscribe for fresh JavaScript tips and tutorials: https://www.youtube.com/@ModernJavaScript?view_as=subscriber?sub_confirmation=1