Home >Web Front-end >JS Tutorial >How to Format Numbers as Currency Strings in JavaScript?
Problem Statement:
In JavaScript, the task is to format a price as a currency string. Specifically, the goal is to create a function that takes a float as an argument and returns a string formatted as "$ 2,500.00".
Solution:
JavaScript offers a convenient solution for this problem through the Intl.NumberFormat API.
Intl.NumberFormat
The Intl.NumberFormat API provides a flexible way to format numbers according to locale-specific rules. To create a currency formatter, we specify the locale and the style:
const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', });
Formatting the Number
Once the formatter is created, we can use it to format a number:
let inputValue = 2500; const formattedValue = formatter.format(inputValue); // Returns "$ 2,500.00"
Customization Options
The Intl.NumberFormat API offers various customization options to adjust the formatting:
Example
The following code snippet demonstrates the use of Intl.NumberFormat with some of the customization options:
// Create number formatter. const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', trailingZeroDisplay: 'stripIfInteger', }); // Get user input. let input = document.getElementById('amount'); // Apply formatting and display the result. input.addEventListener('keyup', e => { const formattedValue = formatter.format(e.target.value); document.getElementById('result').innerText = formattedValue; });
The above is the detailed content of How to Format Numbers as Currency Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!