Home > Web Front-end > JS Tutorial > How to Format Numbers as Currency Strings in JavaScript?

How to Format Numbers as Currency Strings in JavaScript?

Susan Sarandon
Release: 2024-12-31 01:38:09
Original
689 people have browsed it

How to Format Numbers as Currency Strings in JavaScript?

Formatting Numbers as Currency Strings

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',
});
Copy after login

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"
Copy after login

Customization Options

The Intl.NumberFormat API offers various customization options to adjust the formatting:

  • trailingZeroDisplay: Controls the display of trailing zeros. 'stripIfInteger' removes trailing zeros for whole numbers.
  • minimumFractionDigits: Specifies the minimum number of fractional digits to display.
  • maximumFractionDigits: Specifies the maximum number of fractional digits to display.

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;
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template