---
title: "#277: MeasurementFormatter Basics 📐📏"
url: https://littlebitesofcocoa.com/277-measurementformatter-basics
author: Jake Marsh
date: 2016-10-18
published: 2016-10-18
topics: ["Foundation"]
description: "Today we're going to continue our look at the new Measurement functionality in Foundation. (Bite #276). MeasurementFormatter offers some great ways to..."
---

# #277: MeasurementFormatter Basics 📐📏

By Jake Marsh, October 18, 2016. HTML: https://littlebitesofcocoa.com/277-measurementformatter-basics

Today we're going to [continue](https://www.littlebitesofcocoa.com/276) our look at the new `Measurement` functionality in Foundation. ([Bite #276](https://www.littlebitesofcocoa.com/276)). _MeasurementFormatter_ offers some great ways to format and print Strings of our `Measurements`. Let's take a look.

First we'll make define some units to work with. One of the most common ones we'll use in our apps is **Length** (for example when displaying how "far away" something is).

``` swift
let distance = Measurement(value: 1.4, unit: UnitLength.kilometers)
```

Next, we'll make a _formatter_:

``` swift
let formatter = MeasurementFormatter()
```

We'll leave the locale setting alone, which causes it to use the current locale of the device. In our case, `en_US`.

Finally, we'll print the formatted `String`.

``` swift
print(formatter.string(from: distance))
```

Nice. Now we can start to try out some of the options. Let's start with the **style*, we have three choices:

``` swift
formatter.unitStyle = .short // "0.87mi"

formatter.unitStyle = .medium // (the default) "0.87 mi"

formatter.unitStyle = .long // "0.87 miles"
```

We'll use the `.long` style.

By default, our device locale being `en_US` is causing the distance to formatted with "miles" instead of "kilometers" (our input value). We can change this with **unitOptions**:

``` swift
formatter.unitOptions = [.providedUnit]

// "1.4 kilometers"
```

We can even drop down and configure the `NumberFormatter` ([Bite #182](https://littlebitesofcocoa.com/182)) that the `MeasurementFormatter` uses when formatting the numerical part of our `Measurements`:

``` swift
measurementFormatter.numberFormatter.maximumFractionDigits = 0

// "1 mi"
```

Last but not least, we can ask the _formatter_ for a `String` representing <i>only the name</i> of some unit:

``` swift
let formatter = MeasurementFormatter()
formatter.string(from: UnitLength.lightyears)

// "light yrs"
```

Neat!

`MeasurementFormatter` is just another in a long list of wonderful little gems tucked away inside **Foundation**. Know of another that should be covered here? [Send it along!](mailto:hello@littlebitesofcocoa.com?subject=Topic%20Suggestion).
