Splitting Currency Formatting into Components in JavaScript: How to Use Intl.NumberFormat.formatToParts()

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About This Article
This article was generated using an AI-assisted automated workflow. References were made to ECMA-402 and MDN. A browser-based learning tool was created to decompose monetary displays.

Verification Status: ✅ Operation verified in Chromium – Pages publication URL unverified

You want to make only the currency symbol blue, or shrink only the decimal portion. For such use cases, you can use Intl.NumberFormat.formatToParts().

Try It Out First

Live Demo: Currency Display Decomposition Lab(Deployment to Pages unverified)

ItemDescription
TargetModern browsers (verified in Chromium)
RequirementsJavaScript-enabled browser
External librariesNone
InputFictional monetary amounts. No transmission or storage.
NoteThis is not currency conversion

The initial value is 1234.5. The locale is US, and the currency is USD. The currency symbol is displayed in blue. The fractional part becomes smaller.

  1. Change the locale to Germany (de-DE).

  2. Change the currency to EUR.

  3. View the currency symbol position and spacing card.

  4. Click "Invert Sign". A red minus sign is added.

  5. Restore it using "Reset to Initial Value".

The amount display and component card change simultaneously. You can check not only the color, but also the card type and value. Designed to accommodate smartphone operational widths. If the demo does not open,the completed HTML versionshould be saved. Open it in a browser that allows running local HTML. You can also inspect the same components in the Node.js version.

What is the difference?

Displays the same numeric value 1234.5. The results are as follows.

Locale / CurrencyDisplay ExampleFeatures
en-US / USD$1,234.50Symbol at the beginning
de-DE / EUR€1,234.50Symbol at the end
ja-JP / JPY¥1,235No decimals by default

In the German example, the decimal and digit separators are inverted compared to the US. There is also a space before the euro symbol. Japanese yen has zero default decimal places. The decimal part is rounded for display. Fine details such as symbols and spaces depend on the locale data of the runtime environment.

A locale is a value that specifies the display conventions for a language and region. It is a setting separate from the currency code. It is also possible to display US dollars on a Japanese interface. The operation of switching currencies without changing the numeric value is not a conversion.

Understanding the Mechanism

flowchart LR
    A["金額と表示条件"] --> B["Intl.NumberFormat"]
    B --> C["formatToParts()"]
    C --> D["部品の配列"]
    D --> E["順番に画面へ表示"]

This diagram shows the processing order of the demo. When the input changes, components are re-fetched. The screen is also rebuilt. You do not need to calculate the position of the currency symbol yourself. Leave the display order to the API.

Important Parts of the Code

const nf = new Intl.NumberFormat('en-US', {
  style: 'currency', currency: 'USD'
});
const parts = nf.formatToParts(1234.5);
console.log(parts);

style to currency is specified.currency Select the currency as an option.formatToParts() returns an array. Each element contains type and value.

typevaluemeaning
currency$Currency symbol
integer1Part of integer
group,Digit separator
integer234Part of integer
decimal.Decimal separator
fraction50Fractional part

Integers are divided into two parts. If you retrieve only the first integer, it becomes 1. Since 234 disappears, you do not get the entire integer.

For standard display, use format(). That is sufficient. If you want to change the color or size for each component, formatToParts() is suitable.MDN API documentationYou can return to check the return value.

The demo renders each component as follows.price is the HTML element that displays the amount.

for (const part of parts) {
  const span = document.createElement('span');
  span.className = part.type;
  span.textContent = part.value;
  price.append(span);
}

The component type is used as the CSS class. The value is inserted using textContent This is to prevent it from being interpreted as HTML. CSS is used to style the currency symbol and the decimal part. The order of the components themselves does not change.

Change one place and compare

ActionPoints to observe
Keep USD and change the locale to de-DEOnly the formatting conventions change
Change currency to JPYThe default number of decimal places changes
Invert the signminusSign is added (initial US dollar condition)
Leave the amount blankAn error occurs and the old display disappears

Changing two settings at the same time makes it difficult to isolate the cause. Trying one condition at a time reveals the difference. Blank is not the same as 0. The demo treats blank input as an error.

When it does not work properly

SymptomThings to check
Symbol position is incorrectLocale and currency
Integer digits disappearAre all integers being rendered?
Negative sign disappearsAre you discarding the minusSign?
Spaces disappearAre you excluding literals?
Decimals disappearDefault decimal places for currency
Demo does not openPages deployment status and JavaScript enablement

Concatenating all components results in format(), which is identical to the original string. You can use this property to verify the display. The Restored Result in the demo shows this match. However, this match does not guarantee the correctness of financial calculations.

How to use it in your work?

It can be used for product lists and sales dashboards. Even when emphasizing price magnitude, retain the currency and negative sign. Dropping the negative sign from a refund amount reverses its meaning. It is important to display symbols rather than relying solely on color.

Store the original amount and currency code separately. Do not feed the display string back into calculations. Tax calculation and rounding are the responsibility of the calculation logic. This API is a formatting feature for display. In business domains where numerical precision is critical, define dedicated monetary types and rounding rules separately.

For internationalization, set the UI language and transaction currency independently, such as when a user in Japan purchases a US product. Even if the interface is in Japanese, the transaction currency is USD. Some currencies cannot be distinguished by their symbol alone. Include the currency code alongside the symbol when necessary. To assist users who have difficulty distinguishing colors, preserve both the character types and values.

GitHub repository

Glossary

TermMeaning
LocaleA value that specifies display conventions such as language and region
Currency CodeCurrency identifiers such as USD and JPY
DOMA mechanism for programmatically manipulating HTML documents
CSSA mechanism for specifying font colors, sizes, and other styles

Official Information and Verification Scope

The official documentation was re-verified on November 27, 2026. The HTML content was loaded directly in Chromium 144 on 390px and 1200px screens. Initial rendering, region and currency changes, negative signs, Japanese Yen, empty fields, and initialization were verified. Horizontal scrolling and page errors were also inspected. Real devices, Pages public URLs, CodeQL, and actual accounting processes have not been verified.

Document information

Article title
Splitting Currency Formatting into Components in JavaScript: How to Use Intl.NumberFormat.formatToParts()
Published
Updated
Source
https://papanda925.com/?p=18796&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL