Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 146 ยท Standard Library and Foundation

Number and Measurement Formatting

Learn to format numbers in Swift - formatted() styles, NumberFormatter, currency, percent, compact notation, Measurement and units, ByteCountFormatter and Locale, with parsing pitfalls.

print(1234567.891) shows 1234567.891. A person in the United States expects 1,234,567.89; a person in Germany expects 1.234.567,89; someone reading a dashboard wants 1.2M. A price needs a currency symbol, a percentage needs a %, a file size needs KB or MB, and a distance may need kilometers in one country and miles in another. Formatting is the job of turning numbers into text that suits the reader, and doing it right is a large part of an application that feels professional to an international audience.

Swift has two generations of tools for this. The modern one is formatted() with format styles, which is type-safe and composable. The older one is the class family NumberFormatter, MeasurementFormatter and ByteCountFormatter, which you will meet in older code and still need for a few jobs. This lesson shows both, how Locale drives the results, and how to parse numbers back from text. It assumes you know numbers and string formatting.

All examples pass an explicit Locale. Without one, Foundation uses the user's region, which would make this page's output different on different computers.

formatted() on numbers

Every Int, Double, Float and Decimal has a formatted() method. With no arguments you get the default style for the current locale. The interesting part is the style you pass.

Swift Number styles with formatted()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see 1,234,567.891 for the US and 1.234.567,891 for Germany: the separators swap roles. fractionLength(0) rounds to 1,234,568; fractionLength(2) of pi is 3.14; the integer/fraction version pads to 007.0. Grouping can be turned off (1000000), and sign(strategy: .always()) makes positive numbers show a plus: -5 and +5.

The style is a value you can chain, so .number.precision(...).locale(...) reads as "format as a number, with this precision, in this locale". That is the idea behind the whole API.

Percent, currency and compact notation

Swift Percent, currency and compact numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Percent multiplies by 100 for you: 0.256 prints as 25.6% (the default keeps the fraction digits the value needs, and fractionLength(1) pins it). The price renders as $1,499.50 in US English and as 1 499,50 โ‚ฌ in French, with a comma decimal and the euro sign after the number. Japanese yen has no decimals, so 1499.5 is rounded to ยฅ1,500. Compact notation prints short names (1.2M, 3.4K), and scientific notation prints 1.234567E6.

The French output uses a special narrow no-break space between the digits and the symbol, so it looks like a normal space but is not. That detail is a good reason to leave the separators to the library and not assemble numbers by hand.

Do not store money in Double. Binary floating point cannot represent 0.10 exactly, and sums drift (0.1 + 0.2 is not 0.3). Keep prices as integer cents or as Decimal, and use Double only for display math. formatted() works on Decimal too.

Swift Money with Decimal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

0.1 + 0.2 == 0.3 is false, while the Decimal sum is exactly true. The tax of 19.99 ร— 0.0825 is 1.649175, shown rounded to $1.65, and the total displays as $21.64. The last line prints 21.64.

NumberFormatter: the older class

NumberFormatter is configured through properties, then reused. You will find it in a large amount of existing code, and it can do things the style API cannot, such as parsing with leniency. Creating one is costly, so keep the instance and reuse it.

Swift NumberFormatter basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get 1,234.50, 0.50, ยฃ99.00, forty-two, and 3rd 22nd. Notice that you must convert some values to NSNumber (a Foundation class that wraps a number) on Linux, and that the .spellOut and .ordinal styles have no equivalent in the newer API, which is the main remaining reason to reach for NumberFormatter.

Parsing numbers from text

Going the other way, from text to number, is trickier than it looks, because the same characters mean different things in different locales.

Swift Parsing with and without a locale

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Double("3.14") works (Optional(3.14)), but Double("1,234.5") is nil: the plain initializers know nothing about grouping. Int("42 ") with a trailing space is nil, so trim input first, and Int("0x1F") is nil while Int("1F", radix: 16) is Optional(31). With a locale, "1.234,5" parses as 1234.5 in German and "1,234.5" parses as 1234.5 in English. The text "1.234" is 1234.0 (one thousand two hundred thirty-four) in German but 1.234 in English. Never guess; know which locale your input comes from.

Measurements and units

A bare Double has no unit, which is how spacecraft get lost. Measurement pairs a value with a unit, converts between compatible units, and formats with the right names.

Swift Measurement and unit conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The marathon is 42.2 km or 26.22 mi. Adding a kilometer and 500 meters works because both are lengths; Foundation converts to the smaller unit, so both prints show 1500.0 m. Boiling water converts to 212 ยฐF and 373.15 K; temperature units use an offset, not only a factor, and Measurement handles that. The weight is about 5.51 lb. Every Dimension unit has a symbol, and we format the number ourselves with a number style.

Apple platforms also have MeasurementFormatter, which picks units that suit the user's region ("5.2 mi" in the US, "8.4 km" elsewhere). It is not available in swift-corelibs-foundation on Linux, so it cannot run here. The next example shows the real compiler error.

Swift MeasurementFormatter on Linux (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

TEXT
main.swift:3:17: error: 'MeasurementFormatter' is unavailable: Not supported in swift-corelibs-foundation

On an Apple platform this same code compiles. If your code must run on Linux too, format the number and the unit symbol yourself as above.

Mixing incompatible units is not possible: adding a length to a mass is a compile-time error, because Measurement<UnitLength> and Measurement<UnitMass> are different types.

Swift Adding a length and a mass (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with:

TEXT
main.swift:6:27: error: cannot convert value of type 'Measurement<UnitMass>' to expected argument type 'Measurement<UnitLength>'

The note beneath it says the generic arguments UnitMass and UnitLength are expected to be equal. That is the point: the type system catches the unit mix-up before the program runs.

File sizes: ByteCountFormatter

Showing 734003200 bytes as 734 MB is a common need. ByteCountFormatter does it, and you choose the count style: .file uses decimal units like macOS and mobile systems (1 KB = 1000 bytes), .memory uses binary units (1 KB = 1024 bytes), and .decimal and .binary are explicit.

Swift Formatting file sizes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The two columns differ for large sizes: 734,003,200 bytes is about 734 MB in decimal units but 700 MB in binary units. Pick the convention your users expect. Windows traditionally shows binary values with decimal names, a source of "my disk is smaller than advertised" confusion.

Locale: the thing behind all of it

A Locale bundles language, region, number format, currency, calendar and measurement system. Create one by identifier ("en_US", "de_DE", "ja_JP") and read its properties.

Swift What a Locale knows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

For the US you see decimal ., grouping , and USD; Germany swaps the separators and uses EUR; France groups with a space-like character and uses EUR; Japan uses JPY. The last two prints show the language and region parts (en US) and true for the US measurement system.

Two practical rules: format for display with the user's locale (leave off the .locale(...) and the system supplies it), but use a fixed locale (en_US_POSIX) or locale-free code for data that is saved to files or sent over the network. Mixing them up causes bugs such as a CSV file whose numbers use commas in Germany.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does 1234.5.formatted(.number.locale(Locale(identifier: "de_DE"))) produce?

    German uses a period for grouping and a comma as the decimal separator.
  2. 2. Why should you avoid Double for money?

    Use integer cents or Decimal. 0.1 + 0.2 == 0.3 is false for Double.
  3. 3. What does Double("1,234.5") return?

    Use a locale-aware parse such as Double("1,234.5", format: .number.locale(...)) for formatted input.
  4. 4. What happens when you add a Measurement<UnitLength> and a Measurement<UnitMass>?

    The unit type is part of the Measurement type, so unit mix-ups are caught by the compiler.
  5. 5. Which ByteCountFormatter count style treats 1 KB as 1,024 bytes?

    .binary (and .memory) use powers of 1024, while .file and .decimal use powers of 1000.

Summary

  • value.formatted(style) is the modern API. Styles are values that you chain: .number, .percent, .currency(code:), .number.notation(.compactName), .precision(...), .grouping(...), .sign(...), .locale(...).
  • Separators, symbols and the position of the currency sign come from the Locale; pass one explicitly when output must be reproducible.
  • Keep money in Decimal or integer cents, not Double.
  • NumberFormatter is the older class; use it for .spellOut and .ordinal, or when maintaining legacy code, and reuse the instance.
  • Plain Double("...") and Int("...") are locale-free and reject grouping separators and whitespace; parse user-entered text with a locale-aware style.
  • Measurement pairs values with units, converts safely (.converted(to:)) and the compiler rejects incompatible units; MeasurementFormatter is Apple-only.
  • ByteCountFormatter and .byteCount(style:) format sizes; .file is decimal, .binary and .memory are binary.
  • Format for people with the user's locale; use fixed formats for data.

Next: Files and Directories shows how to read and write files with FileManager and URL.